Understanding inheritance is the key to understanding object-oriented programming. In Java, an existing class is inherited through the keyword extends. The inherited class is called the parent class (superclass, base class), and the new class is called the subclass (derived class). Multiple inheritance is not allowed in Java.
(1) Inheritance
class Animal{ void eat(){ System.out.println("Animal eat"); } void sleep(){ System.out.println("Animal sleep"); } void breathe(){ System.out.println("Animal breathe"); } } class Fish extends Animal{ } public class TestNew { public static void main(String[] args) { // TODO Auto-generated method stub Animal an = new Animal(); Fish fn = new Fish(); an.breathe(); fn.breathe(); } } Execute in eclipse:
Animal breathe! Animal breathe!
Each class in the .java file will generate a corresponding .class file under the folder bin. The execution result shows that the derived class inherits all methods of the parent class.
(2) Coverage
class Animal{ void eat(){ System.out.println("Animal eat"); } void sleep(){ System.out.println("Animal sleep"); } void breathe(){ System.out.println("Animal breathe"); } } class Fish extends Animal{ void breathe(){ System.out.println("Fish breathe"); } } public class TestNew { public static void main(String[] args) { // TODO Auto-generated method stub Animal an = new Animal(); Fish fn = new Fish(); an.breathe(); fn.breathe(); } } Execution results:
Animal breatheFish breathe
Define a method in a subclass with the same name as the parent class, the return type, and the parameter type are the same, which is called the override of the method. Overriding methods occurs between subclasses and parent classes. In addition, super can provide access to the parent class.