什么是 Java extends 关键字?
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();
}
}
输出
我的名字是比利我的声音是树皮我的不。腿的长度是 4 我的颜色是棕色 我的品种是拉布拉多 ------------------ 我的名字是 Grace 我的声音是 Bark 我的号。腿的长度是 4 我的颜色是黑色 我的品种是哈士奇 ------------------ 我的名字是 Hugo 我的声音是 Bark 我的号码。腿的长度是 4 我的颜色是灰色 我的品种是贵宾犬
GO TO FULL VERSION