Understanding inheritance is the key to understanding object-oriented programming. In Java, an existing class is inherited by the keyword extends, the inherited class is called the parent class (the superclass, the base class), and the new class is called a subclass (derived class). Multiple inheritance is not allowed in Java.
(1) Inheritance
[Java]View Plaincopy
- 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 ();
- }
- }
In Eclipse execution:
Animal breathe!
Animal breathe!
Each class in the. java file generates a corresponding. class file under the folder bin. The execution result shows that the derived class inherits all the methods of the parent class.
(2) Coverage
[Java]View Plaincopy
- 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 Result:
Animal Breathe
Fish Breathe
A method that defines the same name, return type, and parameter type of the parent class in the subclass is called the override of the method. The override of the method occurs between the child class and the parent class. In addition, you can provide access to the parent class with super.
Reference Original: http://blog.csdn.net/zhandoushi1982/article/details/5441126
Extends usage of Java