본문 바로가기

기록(노트)

상속(부모,자식객체)

상속

전화걸기

package practice;

public class Phone {
    //field declaration
    public String model;
    public String color;

    //method decalration;
    public void bell() {
        System.out.println("Ring goes off!");
    }
    public void sendVoice(String message) {
        System.out.println("Me: "+ message);
    }
    public void receiveVoice(String message) {
        System.out.println("you: " + message);
    }
    public void hangUp() {
        System.out.println("hung up the phone");
    }

}

객체내부(설계도:부모객체)

 

 

package practice;

public class SmartPhone extends Phone {
    //field declaration
    public boolean wifi;

    //constructor declaration
    public SmartPhone(String model, String color) {
        this.model = model;
        this.color = color;
    }

    //method declaration
    public void setWifi(boolean wifi) {
        this.wifi = wifi;
        System.out.println("Wifi has changed");
    }
    public void internet() {
        System.out.println("internet has been connected");
    }
}

객체내부(설계도:자식객체)

public class SmartPhone extends Phone {
}

 

 

 

package practice;

public class SmartPhoneExample {
    public static void main(String[] args) {
        //smartphone object creation
        SmartPhone myPhone = new SmartPhone("Galaxy", "grey");

        //Read field taken over by Phone
        System.out.println("Model: " + myPhone.model);
        System.out.println("Color: " + myPhone.color);

        //Read field "SmartPhone"
        System.out.println("Wifi: " + myPhone.wifi);

        //Declare method taken over by Phone
        myPhone.bell();
        myPhone.sendVoice("Hello?");
        myPhone.receiveVoice("Hello, This is Haribo.");
        myPhone.sendVoice("Hey, How is it going?");
        myPhone.hangUp();

        //Delare method of SmartPhone
        myPhone.setWifi(true);
        myPhone.internet();
    }
}

외부 객체(호출)

 

정답:

Model: Galaxy
Color: grey
Wifi: false
Ring goes off!
Me: Hello?
you: Hello, This is Haribo.
Me: Hey, How is it going?
hung up the phone
Wifi has changed
internet has been connected

Process finished with exit code 0