Characteristics of the object-oriented inheritance

Inheritance reasons:

When the presence of the same properties and behavior of the plurality of classes 1, these contents drawn into a single class,

So more than one class do not need to define these properties and behavior, as long as you can inherit that class.

2. The plurality of class herein referred to as a subclass (derived class), a separate class is called the parent class (superclass or base class).

Can be understood as: "parent class is a subclass of"

Grammar rules:

class 子类Subclass extends SuperClass父类{}

 Inherit the role:

1. The emergence of inherited reduce code redundancy and improve the reusability of code.

2. The emergence of inheritance, more conducive to extended functions.

3. The emergence of inheritance between classes so that had a relationship, it provides a prerequisite of polymorphism.

Precautions:

1. subclass inherits the parent class, it inherits the methods and properties of the parent class.

2. subclasses methods and properties of the parent class definition, can also create new data and methods.

3. The keyword is inherited extends, that is a subset of the parent class is not a class, but the parent class of "extended."

4. subclass can not directly access member variables and methods of the parent class private (Private) a.

 5.Java only supports single inheritance and multiple inheritance, multiple inheritance is not allowed.

  ➢ a subclass of only one parent class
  ➢ a parent class subclasses can be derived

 1 public class Creature {    
 2     public void breath(){
 3         System.out.println("呼吸");
 4     }    
 5 }
 6 
 7 class Person extends Creature{    
 8     String name;
 9     private int age;
10     
11     public Person(){        
12     }
13     
14     public Person(String name,int age){
15         this.name = name;
16         this.age = age;
17     }
18     
19     public void eat(){
20         System.out.println("吃饭");
21         sleep();
22     }
23     
24     private void sleep(){
25         System.out.println("睡觉");
26     }
27     public int getAge() {
28         return age;
29     }
30     public void setAge(int age) {
31         this.age = age;
32     }
33     
34 }

Guess you like

Origin www.cnblogs.com/ZengBlogs/p/12158011.html