Java 확장 키워드란 무엇입니까?
class ParentClass{ ...}
class ChildClass extends ParentClass { ... }
Java의 상속은 무엇입니까?
Java에서 extends 키워드 의 사용법을 이해하려면 먼저 상속의 개념을 이해하는 것이 중요합니다. Java는 객체 지향 프로그래밍(OOP) 언어입니다. OOP는 클래스와 객체를 사용하여 프로그램을 설계하는 방법입니다. 클래스와 객체를 다룰 때 표현해야 하는 서로 다른 클래스 간에 특정 관계가 있을 수 있습니다. 상속은 클래스 간의 관계 중 하나입니다. 상속은 개체 간의 Is-A-Relationship을 나타냅니다. 상속은 한 클래스가 다른 클래스의 속성을 획득하는 메커니즘으로 정의할 수 있습니다. 상속받는 클래스를 자식 클래스 또는 하위 클래스라고 하고 상속되는 클래스를 부모 클래스 또는 슈퍼 클래스라고 합니다. 확장하다Java에서 클래스 간의 상속을 수행하는 데 사용되는 키워드입니다.예
Java extends 키워드의 예는 다음과 같습니다.class Animal {
// fields of the parent class
String name;
String sound;
int noOfLegs;
// default constructor of the parent class
public Animal (){}
// parameterized constructor of the parent class
public Animal (String name, String sound, int legs){
this.name = name;
this.sound = sound;
this.noOfLegs = legs;
}
// method of the parent class
public void display() {
System.out.println("My name is " + name);
System.out.println("My sound is " + sound);
System.out.println("My no. of legs is " + noOfLegs);
}
}
// inherit from Animal
class Dog extends Animal {
String color;
String breed;
// new method in subclass
public Dog(String name, String sound ,int legs, String color, String breed){
super(name,sound,legs);
this.color = color;
this.breed = breed;
}
public void display() {
super.display();
System.out.println("My color is " + color);
System.out.println("My breed is " + breed);
}
}
public class Main {
public static void main(String[] args) {
// create an object of the subclass
Dog dog1 = new Dog("Billy","Bark",4,"Brown","Labrador");
dog1.display();
System.out.println("------------------");
Dog dog2 = new Dog("Grace","Bark",4,"Black","Husky");
dog2.display();
System.out.println("------------------");
Dog dog3 = new Dog("Hugo","Bark",4,"Gray","Poodle");
dog3.display();
}
}
산출
내 이름은 Billy 내 소리는 Bark My no. 내 색깔은 갈색 내 품종은 래브라도 ------------------ 내 이름은 그레이스 내 소리는 바크 내 no. 내 색깔은 검은색 내 품종은 허스키 ------------------ 내 이름은 Hugo 내 소리는 Bark 내 no. 다리 길이는 4입니다. 내 색깔은 회색입니다. 내 품종은 푸들입니다.