package kr.s17.object.overriding;
//부모 클래스
class Parent{
int a = 100;
public void play() {
System.out.println("Parent의 play 메서드");
}
}
//자식클래스
class Child extends Parent {
int a = 200;
//생성자를 만들어서 호출
public Child() {
System.out.println(super.a);
super.play();
System.out.println("------------------------");
}
@Override
public void play() {
System.out.println("Child의 play 메서드");
}
}
public class SuperMain01 {
public static void main(String[] args) {
Child ch = new Child();
System.out.println(ch.a);
ch.play();
}
}
100
Parent의 play 메서드
------------------------
200
Child의 play 메서드
package kr.s17.object.overriding;
//부모클래스
class People{
int a = 100;
//생성자
public People() {
super(); //부모클래스 Object의 기본 생성자 호출
}
}
//자식클래스
class Student extends People{
int b = 200;
//생성자(쓰지않아도 자동으로 들어가있음)
public Student() {
super();//부모클래스(People)의 기본 생성자 호출
}
}
public class SuperMain02 {
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.a);
System.out.println(s.b);
}
}
100
200
package kr.s17.object.overriding;
//부모클래스
class People2{
int a;
public People2(int a) {
this.a =a;
}
}
//자식 클래스
class Student2 extends People2 {
//생성자
public Student2 () {
//부모클래스의 자료형이 int인 인자를 가지고 있는 생성자 호출
super(700);//위에 생성자를 의미 700은 a로 전달
}
}
public class SuperMain03 {
public static void main(String[] args) {
Student2 st = new Student2();
System.out.println(st.a);
}
}
700
package kr.s17.object.overriding;
//부모클래스
class Point{
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String getLocation() {
return"x : " + x +" , y : "+y;
}
}
//자식 클래스
class Point3D extends Point{
int z;
public Point3D(int x, int y, int z) {
//Point 부모클래스의 int형 인자가 2개인 생성자를 호출
super(x,y);
this.z = z;//z는 부모클래스가 아니기 때문에 따로 해줘야됨.
}
@Override
public String getLocation() {
return "x :" + x + ", y :" +y + ", z :" +z;
}
}
public class SuperMain04 {
public static void main(String[] args) {
Point3D p3 = new Point3D(10,20,30);
System.out.println(p3.getLocation());
}
}
x :10, y :20, z :30