java中实现多继承
Java继承 (Java Inheritance )
Inheritance in Java is a methodology by which a class allows to inherit the features of other class.
Java中的继承是一种允许类继承其他类的功能的方法。
It is also known as IS-A relationship.
也称为IS-A关系 。
By using extends keyword we can implement inheritance in java.
通过使用extends关键字,我们可以在java中实现继承 。
The advantage of inheritance is reusability of code.
继承的优点是代码的可重用性。
Important terms related to inheritance:
与继承相关的重要术语:
Parent class:
家长班:
It is also known as a superclass or base class and the definition of the parent class is the class whose properties (or features) is inherited.
也称为超类或基类,父类的定义是继承其属性(或功能)的类。
Child class:
子班:
It is also known as a subclass or derived class and the definition of the child class is the class that inherits the properties (or features) of other class.
它也称为子类或派生类,子类的定义是继承其他类的属性(或功能)的类。
如何在Java中实现继承? (How to implement inheritance in java?)
We implement inheritance with the help of extends keyword.
我们借助extends关键字实现继承 。
Syntax:
句法:
class Parent {
public void method1() {
// Fields and Statement
}
}
class Child extends Parent {
public void method2() {
// Fields and Statement
}
}
Example:
例:
In below example of inheritance, class Parent is a superclass, class Child is a subclass which extends the Parent class.
在下面的继承示例中 , Parent类是父类, Child类是扩展Parent类的子类。
/*Java program to demonstrate the
concept of inheritance */
// Parent class
class Parent {
// The Parent class has one method
// displayParentMessage() method to print message of Parent Class
public void displayParentMessage() {
System.out.println("Hello, we are in parent class method");
}
}
// Sub class or derived class
class Child extends Parent {
// The Child subclass adds one more method
// displayChildMessage() method to print message of Parent Class
public void displayChildMessage() {
System.out.println("Hello, we are in child class method");
}
}
// Main class in this class we will create
//object of parent and child class
class Main {
public static void main(String[] args) {
// Creation of Parent class object
Parent p = new Parent();
// Calling Parent class method by Parent class object
p.displayParentMessage();
// Creation of Child class object
Child c = new Child();
// Calling Child class method by Child class object
c.displayChildMessage();
// Calling Parent class method by Child class object
c.displayParentMessage();
}
}
Output
输出量
D:\Programs>javac Main.java
D:\Programs>java Main
Hello, we are in parent class method
Hello, we are in child class method
Hello, we are in parent class method
翻译自: https://www.includehelp.com/java/inheritance-and-its-implementation-in-java.aspx
java中实现多继承