본문 바로가기
JAVA

상속

by KWONE 2024. 8. 14.

  
class Point{
private int x,y;
public void set(int x, int y) {
this.x=x;
this.y=y;
}
public void showPoint() {
System.out.println("(" + x + "," + y + ")");
}
}
class ColorPoint extends Point{
private String color;
public void setColor(String color) {
this.color=color;
}
public void showColorPoint() {
System.out.print(color);
showPoint();
}
}
public class ColorPointEx {
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();
}
}

supper()이용한 생성자 선택


  
class Point{
private int x,y;
public Point() {
this.x=this.y=0;
}
public Point(int x, int y) {
this.x=x;
this.y=y;
}
public void showPoint() {
System.out.println("(" + x + "," + y + ")");
}
}
class ColorPoint extends Point{
private String color;
public ColorPoint(int x, int y, String color) {
super(x,y);
this.color=color;
}
public void showColorPoint() {
System.out.println(color);
showPoint();
}
}
public class SuperEx {
public static void main(String[] args) {
ColorPoint cp=new ColorPoint(5,6,"blue");
cp.showColorPoint();
}
}

'JAVA' 카테고리의 다른 글

클래스와 객체 활용 예제  (0) 2024.08.16
@Override  (0) 2024.08.15
Chapter 03 실습문제  (0) 2024.08.13
비정형 배열  (0) 2024.08.13
생성자  (0) 2024.08.13