본문 바로가기

자바

접근지정자, super()

30) 접근지정자, super()

package school;

 

public class Point {

private int x, y; // private이기에 Point 클래스의 set, showpoint에서만 접근가능

// private 멤버: 서브, 자식 클래스에서 접근 불가

// 디폴트 멤버: 서브 클래스가 동일한 패키지에 있을때에만 접근가능

// public 멤버: 항상 접근 가능

// protected 멤버: 같은 클래스와 자식 클래스인 경우에만 가능

public void set(int x, int y) { this.x=x; this.y=y; }

public void showPoint() { System.out.println("("+x+","+y+")"); }

public Point() { this.x=this.y=0;}

public Point(int x, int y) {this.x=x; this.y=y;}

}

 

public class ColorPoint extends Point{ // 부모클래스(Point) 상속

private String color;

public void setColor(String color) { this.color=color;}

public void showColorPoint() {

System.out.print(color);

showPoint();

}

public ColorPoint(int x, int y, String color) {

super(x,y); // super()를 사용하여 부모 생성자 명시적 선택

// 반드시 첫라인에 위치

// 명시적으로 선택하지 않는 경우 부모의 기본 생성자 선택

// 만약 super(x,y) 미작성시 Point.Point() 선택

this.color=color;

}

public ColorPoint() {color="white";}

}

 

public class temp6 {

 

public static void main(String[] args) {

Point p=new Point();

p.set(1,2);

p.showPoint();

 

ColorPoint cp= new ColorPoint();

cp.set(3,4);

cp.setColor("red");

cp.showColorPoint();

 

ColorPoint cp2= new ColorPoint(5,6,"blue");

cp.showColorPoint();

 

ColorPoint cp3= new ColorPoint();

cp2.showColorPoint();

}

}