IT/Java
자바 상속 두번째 예제
노마드오브
2018. 7. 17. 00:07
파일명 : Test2.java
package com.test;
// Point2D 클래스
// 멤버변수 정수형 x y
// 메소드 prn2D() 출력 "x, y"
class Point2D { // 2차원 좌표
int x, y;
void prn2D() {
System.out.println(x+", "+y);
}
}
// Point3D 클래스
// 멤버변수 정수형 z
// 메소드 prn3D 출력 "x, y, z"
class Point3D extends Point2D {
int z;
void prn3D() {
System.out.println(x+", "+ y+", "+z);
}
}
public class Test2 {
public static void main(String[] args) {
// Point3D 객체생성
Point3D p = new Point3D();
// x 10 y 20 z 30
p.x = 10; // new Point3D() 객체 기준으로 접근하는 것이 아니라, Point3D p를 기준으로 컴파일러가 확인한다.
p.y = 20; // p가 null이더라도 컴파일 오류 발생 안함
p.z = 30;
// 메소드 호출 prn2D prn3D
p.prn2D();
p.prn3D();
}
}