728x90
//--------------------------------------------------------------------------
class Parent {
int x = 10;
}
//--------------------------------------------------------------------------
class Child extends Parent {
void method() {
System.out.println("x -> " + x);
System.out.println("this.x -> " + this.x);
System.out.println("super.x -> " + super.x);
}
}
//--------------------------------------------------------------------------
public class SuperExam {
public static void main(String[] args) {
Child c = new Child();
c.method();
}
}
// 출력 결과
x -> 10
this.x -> 10
super.x -> 10
//--------------------------------------------------------------------------
class Parent {
int x = 10;
}
//--------------------------------------------------------------------------
class Child extends Parent {
int x = 20;
void method() {
System.out.println("x -> " + x);
System.out.println("this.x -> " + this.x);
System.out.println("super.x -> " + super.x);
}
}
//--------------------------------------------------------------------------
public class SuperExam {
public static void main(String[] args) {
Child c = new Child();
c.method();
}
}
// 출력 결과
x -> 20
this.x -> 20
super.x -> 10
//--------------------------------------------------------------------------
class Point {
int x;
int y;
Point() {} // super();에 매개변수 전달해주거나 매개변수없는 기본생성자를 만들어줘야함.
Point(int x, int y) {
this.x = x;
this.y = y;
}
String getLocation() {
return "x:" + x + ", y:" + y;
}
}
//--------------------------------------------------------------------------
// Object 클래스를 제외한 모든 클래스의 생성자 첫 줄에는
// 생성자(같은 클래스와 다른 클래스 생성자 또는 조상의 생성자)를 호출해야 한다.
// 그렇지 않으면 컴파일러가 자동적으로 super();를 생성자의 첫 줄에 만들어준다.
//--------------------------------------------------------------------------
class Point3D extends Point {
int z;
Point3D(int x, int y, int z) {
super(); // 위에 매개변수 없는 기본생성자를 만들어 주거나 super(1, 2) 안에 이런식으로 매개변수 전달 해줘야 함
this.x = x;
this.y = y;
this.z = z;
}
String getLocation() { // 오버라이딩
return "x:" + x + ", y:" + y + ", z:" + z;
}
}
//--------------------------------------------------------------------------
public class PointExam {
public static void main(String[] args) {
Point3D p3 = new Point3D(1, 2, 3);
System.out.println(p3.getLocation());
}
}
// 출력 결과
x:1, y:2, z:3
'Language > Java' 카테고리의 다른 글
[Java] 정리 (상속(inheritance)) (0) | 2022.08.12 |
---|---|
[Java] 실습 (단일 상속) (0) | 2022.08.12 |
[Java] 실습 (Overriding Overloading) (0) | 2022.08.12 |
araFarm (0) | 2022.08.11 |
[Java] 메소드 오버로딩 (Method Overloading) (0) | 2022.08.11 |