Java-6.2 inheritance (Generalization) (1)
Let's talk about inheritance in this chapter ).
1. Concept
Inheritance is to derive a new class from an existing class. The new class can absorb the data attributes and behaviors of the existing class and expand new capabilities.
2. Features
Subclass inherits the attribute fields and methods of the parent class public and protected, but does not inherit the attribute fields and methods of private.
If required, override (@ override) to implement the method of the basic parent class of the subclass.
The following is an example.
Package com. ray. testobject; public class Test {public static void main (String [] args) {}} class Father {private int id; protected String name; public int sex; private void methodA () {} protected void methodB () {} public void methodC () {} public Father () {System. out. println (create father);} class Sub extends Father {@ Overrideprotected void methodB () {// TODO Auto-generated method stubsuper. methodB () ;}@ Overridepublic void methodC () {// TODO Auto-generated method stubsuper. methodC ();} public Sub () {System. out. println (create Sub); // System. out. println (id); // error System. out. println (name); System. out. println (sex );}}
3. Relationships with parent classes
We can modify the above Code to explain that is-a is like is-like-.
Package com. ray. testobject; public class Test {public static void main (String [] args) {}} class Father {private int id; protected String name; public int sex; private void methodA () {} protected void methodB () {} public void methodC () {} public Father () {System. out. println (create father) ;}} class Sub1 extends Father {public Sub1 () {System. out. println (create Sub); // System. out. println (id); // error System. out. println (name); System. out. println (sex) ;}} class Sub2 extends Father {private void say () {} public Sub2 () {System. out. println (create Sub); // System. out. println (id); // error System. out. println (name); System. out. println (sex );}}
Let's take a look at the above Code. sub1 directly inherits father and there are no other different methods. Therefore, sub1 is a sub-class of father and is a-a relationship;
In addition to inheriting father, sub2 also has a say method, so it is not exactly the same as father. Therefore, although sub2 is a subclass of father, however, the direct relationship between them is-like-.
Summary: This chapter mainly discusses the concept and features of inheritance and the relationship between subclasses and parent classes.