Understanding inheritance is the key to understanding object-oriented programming. In Java, an existing class is inherited by using the keyword extends. The inherited class is called the parent class (superclass, base class), and the new class is called the subclass (derived class ). Many 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 stubAnimal an = new Animal();Fish fn = new Fish();an.breathe();fn.breathe();}}
Run the following command in Eclipse:
Animal breathe!
Animal breathe!
Each class in the. Java file will generate a corresponding. Class file under the bin folder. The execution result indicates 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 stubAnimal an = new Animal();Fish fn = new Fish();an.breathe();fn.breathe();}}
Execution result:
Animal breathe!
Fish bubble
Define a method in the subclass that has the same name as the parent class, and has the same return type and parameter type. It is called method overwrite. Method overwrites occur between the subclass and parent class. In addition, super can be used to provide access to the parent class.
Http://tieba.baidu.com/F? Kz= 295170500
Http://zhidao.baidu.com/question/25517733.html ()