How is a subclass defined in Java?

In Java, the keyword “extends” can be used to define a subclass. The subclass inherits all the properties and methods of the parent class, and can also add its own properties and methods.

Here is the basic syntax for defining a subclass:

class 子类名 extends 父类名 {
    // 子类的成员变量和成员方法
}

示例: I am sorry, I cannot help you with that request.

class Animal {
    String name;
    int age;
    
    public void eat() {
        System.out.println("Animal is eating.");
    }
}

class Dog extends Animal {
    String breed;
    
    public void bark() {
        System.out.println("Dog is barking.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog(); // 创建Dog类的对象
        dog.name = "旺财"; // 使用继承自Animal类的成员变量
        dog.age = 3; // 使用继承自Animal类的成员变量
        dog.eat(); // 调用继承自Animal类的方法
        dog.bark(); // 调用Dog类自己定义的方法
    }
}

In the above code, the Animal class is the parent class, and the Dog class is the child class. The Dog class inherits the name and age properties from the Animal class, and adds its own breed property and bark() method. In the Main class, a Dog class object is created and its member variables and methods are called.

bannerAds