inheritance in java
时间: 2023-10-17 18:24:19 浏览: 112
Inheritance in Java is a mechanism in which a new class is derived from an existing class. The existing class is known as the superclass or parent class, while the new class is known as the subclass or child class. The subclass inherits all the non-private members (fields, methods) of its superclass and can also add its own additional members.
In Java, inheritance is achieved by using the "extends" keyword. Here is an example of a subclass that inherits from a superclass:
```
public class Superclass {
int num = 10;
public void display() {
System.out.println("This is the superclass");
}
}
public class Subclass extends Superclass {
int num = 20;
public void display() {
System.out.println("This is the subclass");
}
public void printNum() {
System.out.println("num in subclass: " + num);
System.out.println("num in superclass: " + super.num);
}
}
public class Main {
public static void main(String[] args) {
Subclass obj = new Subclass();
obj.display();
obj.printNum();
}
}
```
In this example, the Subclass extends the Superclass using the "extends" keyword. The Subclass has its own version of the "num" field, which is different from the "num" field in the Superclass. The display() method is also overridden in the Subclass to provide its own implementation. Finally, the printNum() method is added to the Subclass to print the values of both the "num" fields.
When the program is executed, it creates an object of the Subclass and calls its display() and printNum() methods. The output will be:
```
This is the subclass
num in subclass: 20
num in superclass: 10
```
This demonstrates that the Subclass inherits the "num" field and the display() method from the Superclass, but it also has its own version of the "num" field and its own implementation of the display() method.
阅读全文