1 /*2 Considerations for Inheritance:3 A: Subclasses can only inherit all non-private members of the parent class (member methods and member variables)4 B: Subclasses cannot inherit the constructor of the parent class, but can access the parent class construction method through the super (immediately speaking) keyword. 5 C: Do not inherit for part of the function6 class A {7 Public void Show1 () {}8 Public void Show2 () {}9 }Ten One class B { A Public void Show2 () {} - Public void Show3 () {} - } the - //We found that the Show2 () method is the same as Class A in class B, so we use inheritance to show - class B extends A { - Public void Show3 () {} + } - This is actually not good, because you have not only show2 (), but also more show1 (). + It is possible that show1 () is not what you want. A at So, when do we think about using inheritance ? - inheritance actually embodies a relationship: "is a". - Person - Student - teacher// Teacher is a person, student is also a person - Fruit in Apple - Banana to oranges// apples are fruits, bananas are fruits, oranges are fruits too . + - adopt the Hypothesis method. the If there are two classes, a, B. Only if they meet the one of A is B, or B is a, you can consider using inheritance. * */ $ classFather {Panax Notoginseng Private intnum = 10; - Public intnum2 = 20; the + //private methods, subclasses cannot inherit A Private voidmethod () { the System.out.println (num); + System.out.println (num2); - } $ $ Public voidShow () { - System.out.println (num); - System.out.println (num2); the } - }Wuyi the classSonextendsFather { - Public voidfunction () { Wu //num can access private in Father - //System.out.println (num);//subclasses cannot inherit private member variables of parent class About System.out.println (num2); $ } - } - - classExtendsDemo3 { A Public Static voidMain (string[] args) { + //Creating Objects theSon s =NewSon (); - //S.method ();//subclasses cannot inherit private member methods of parent class $ s.show (); the s.function (); the } the}
Android (Java) Learning Note 118: Considerations for Class inheritance