JAVA
Inheritance
seoca
2019. 1. 3. 07:02
Inheritance 상속
Inheritance in Java, it allows that a child class can acquire the features from a parent class, to avoid duplicate code and it is easy to maintain the program.
다른 클래스의 기능을 사용하고 싶을때 상속을 통해서 자식 클래스가 부모클래스의 기능을 그대로 사용할 수 있다. 그로인해 코드의 중복을 피할 수 있고 유지보수 또한 편리해지는 장점(하나가 변하면 다른 쪽도 자동으로 영향을 받기에)을 얻을 수 있다.
extends keyword syntax
class Bird extends Animal
-> Class Bird inherits its super class Animal
Example code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Animal{ void walk(){ System.out.println("I am walking"); } } class Bird extends Animal{ //-> class Bird 는 Animal class 를 상속 받는다. void fly(){ System.out.println("I am flying"); } void sing(){ System.out.println("I am singing"); } } public class Solution{ public static void main(String args[]){ Bird bird = new Bird(); bird.walk(); bird.fly(); bird.sing(); } } | cs |