Java notes--inheritance

Source: Internet
Author: User

Read Catalogue
    • Role
    • Super keyword
    • Access control permissions
    • Order of initialization
    • @Override and Method overrides
    • Inheriting abstract classes
    • Final keyword
First, the role

1) Reuse Class


[Back to top]


Second, super keyword

1) First usage: Super keyword is a reference to the parent class object

Package Com.example;public class person{//Parent public String name= ' Zhang San ';p ublic int age = 20;public void speak () {SYSTEM.OUT.P Rintln ("Person:speak ()");} public void Cry () {System.out.println ("person:cry ()");}}
Package Com.example;public-Class man extends person{//subclass public void Speak () {System.out.println ("man:speak ()"); Super.speak (); Call the parent class's speakcry (); Call the parent class's CrySystem.out.println ("Name:" + name); Call the parent class's NameSystem.out.println ("Age:" + super.age); Call the parent class's Age}}
Package Com.example;public class Test{public static void Main (string[] args) {mans m = new Man (); M.speak ();}}
Run Result: Man:speak () Person:speak () person:cry () name: Zhang San age:20
    • There are speak methods in both the parent and child classes, so when you want to invoke the Speak method of the parent class in the subclass, you must use the Super keyword (in which case the subclass has overridden the parent class's method)
    • Other situations can also be used without using the Super keyword, for example: Cry (), name, super.age in the example
    • In fact, when creating a subclass object, the parent object is created first, and the parent object is wrapped in a subclass object (it can be imagined that there is a line of code in the man object that has person super = new person (), where super is a reference to the parent class object)

2) Second usage: super () or super (argument list) is the constructor of the parent class

Example 1:

Package Com.example;public class person{//Parent Public person () {System.out.println (' person () ')}}
Package Com.example;public-Class man extends person{//Subclass Public Man () {super ();//Parent Constructor System.out.println ("Man ()");//Su Per (); Error}}
Package Com.example;public class Test{public static void Main (string[] args) {new Man ();}}
Run Result: Person () man ()
    • The parent class constructor can only be called in the subclass constructor and cannot be called in a method of a subclass
    • The parent class constructor can only be located in the first row of the child class constructor
    • Each subclass constructor can call only one parent class constructor

Example 2:

Package Com.example;public class person{//Parent Public person (int. i) {System.out.println ("person" + "(" + i + ")");} Public person (String str) {System.out.println ("person" + "(" + str + ")");}}
Package Com.example;public-Class man extends person{//Subclass Public Man () {super (1);//Call the parent class constructor System.out.println ("Man ()");} Public man (int i) {super ("Zhang San");//Call the parent class constructor System.out.println ("Man" + "(" + i + ")");} Public man (String str) {super (2);//Call the parent class constructor System.out.println ("Man" + "(" + str + ")");}
Package Com.example;public class Test{public static void Main (string[] args) {new Man ();}}
Run Result: Person (1) man ()
    • If we do not create a constructor for the class, the compiler automatically creates a default constructor for the class (without the parameter constructor), which is done at compile time and is not visible to us. If we create a constructor for a class, the compiler will no longer create a default constructor for the class
    • When the parent class contains a default constructor, the compiler automatically calls the parent class's default constructor in the child class's constructor to complete the initialization of the parent class, which is also done at compile time, and we cannot see
    • When the parent class contains a parameterless constructor, the compiler also automatically calls the parent class's parameterless constructor in the subclass constructor
    • When a parent class contains only a parameter constructor, the compiler does not automatically invoke the constructor of the parent class in the subclass constructor, and we must call a constructor in the parent class in all the constructors of the subclass, or else compile with an error, for example: example, each constructor in the neutron class man invokes the constructor of the parent class
    • Summary: In an inheritance relationship, the parent is best not to create a constructor or to create a parameterless constructor when creating multiple constructors, so that the constructors for each subclass are not invoked on the constructor of the parent class

[Back to top]


Third, access control permissions

1) Java access control permissions are public,protected,<default>,private if inheritance relationships are not involved, protected and <default> can only be accessed within the package

Package Net.example;public class S{public int i = 10;protected double d = 51.2; String str1 = "Zhang San"; <default>private String str2 = "John Doe"; }
Package Com.example;public class T{public int i = 10;protected double d = 51.2; String str1 = "Zhang San"; <default>private String str2 = "John Doe";}
Package Com.example;import NET.EXAMPLE.S; Import S class public class Test{public static void Main (string[] args) {s S1 = new S (); System.out.println ("s:" + s1.i);//system.out.println ("s:" + s1.d); Error//system.out.println ("S:" + s1.str1); Error//system.out.println ("S:" + s1.str2); Errort T1 = new T (); System.out.println ("T:" + t1.i); System.out.println ("T:" + t1.d); System.out.println ("T:" + t1.str1);//system.out.println ("T:" + T1.STR2); Error}}
Operation Result: s:10t:10t:51.2t: Zhang San
    • Private can be accessed across packages
    • When there are no inheritance relationships, protected and <default> are only accessible within the package. Examples of test and T in the same package, test and S are in different packages, so s1.d and S1.STR1 are not compiled, and t1.d and T1.STR1 can be compiled by
    • Private can only be accessed in the same class

2) Subclasses can access properties and methods that are restricted by protected in the parent class, even if the subclass and parent class are not in the same package

Package Net.example;public class animals{//parent class protected int = 2; String name = "Wang Choi"; <default>protected void Bark () {System.out.println ("barking");}}
Package Com.example;import net.example.Animals; Import Animals class public class Dogs extends animals{//Subclass public Dogs () {System.out.println (age);//system.out.println (name); Errorbark ();}}
Package Com.example;public class Test{public static void Main (string[] args) {new Dogs ();}}
Operation Result: 2 bark
    • The access control permission for the Name property in the parent class is <default>, so the child class cannot invoke the property
    • Protected access control permissions guarantee that only the inheritors can access the properties and methods of the parent class, although in the case of a cross-package, if a class and the parent class are in the same package, even if the class does not inherit the parent class, you can also freely access the properties and methods in the parent class that are restricted by protected
3) Subclasses to override a method in a parent class, the access control permission for the method overridden in the subclass must be higher than the access control permission of the parent class's method
Package Com.example;public class person{//Parent public void P1 () {System.out.println ("Person:p1");} protected void P2 () {System.out.println ("Person:p2");} void P3 () {System.out.println ("person:p3");} private void P4 () {System.out.println ("Person:p4");}}
Package Com.example;public-Class man extends person{//subclass public void P1 () {System.out.println ("Man:p1");} /* public void P2 () {System.out.println ("Man:p2");} */protected void P2 () {System.out.println ("Man:p2");} /* void P2 () {//error, Protected's access control permission is higher than <default> System.out.println ("Man:p2");} */  * public void P3 () {Sy Stem.out.println ("Man:p3");} protected void P3 () {System.out.println ("Man:p3"),} */void P3 () {System.out.println ("man:p3");} /* public void P4 () {System.out.println ("Man:p4");} protected void P4 () {System.out.println ("Man:p4");} void P4 () {System.out.println ("Man:p4"),} */private void P4 () {System.out.println ("Man:p4");}}
Package Com.example;public class Test{public static void Main (string[] args) {mans m = new Man (); M.p1 (); M.p2 (); M.p3 ();//M.P 4 (); Error}}
Running Result: MAN:P1MAN:P2MAN:P3
    • The P2 method in the subclass man cannot be overridden with <default> access control permissions because the protected has higher control permissions
    • M.P4 () cannot be called in the Test class because the access control permission for P4 () is private and can only be called inside the class
    • When a subclass overrides a method of a parent class, as long as the overridden method's access control permission is higher than the parent class, such as: The P2 method in the parent class is limited by protected, so when the subclass man overrides the P2 method of the parent class, it can be public or protected, but not <defa Ult> and private

[Back to top]


Iv. sequence of initialization

1) Initialization order: Parent class static property, Subclass static property, parent non-static property, parent class constructor call, subclass non-static property--subclass constructor Call

Package Com.example;public class T{public T (int i) {System.out.println ("T" + "(" + i + ")");}}
Package Com.example;public class person{//Parent public static T T1 = new T (1);//static property public T t2 = new T (2);//non-static property public Person () {System.out.println (' person () ');} public static T t3 = new T (3); Static Property}
Package Com.example;public class Man extends person{//subclass public static T T4 = new T (4);//static property public T T5 = new T (5); Non-static property public mans () {System.out.println ("Man ()");} public static T T6 = new T (6); Static Property}
Package Com.example;public class Test{public static void Main (string[] args) {new Man ();}}
Running Result: t (1) T (3) T (4) T (6) T (2) person () T (5) Man ()

[Back to top]


V. @Override and Method rewriting

1) Java in order to ensure that the method overrides are not erroneously written method overloading, so the introduction of the @Override

Package Com.example;public class person{//Parent public void speak (int i) {System.out.println ("Person:speak" + "(" + i + ")") ;}}
Package Com.example;public class Man extends person{//subclass/* @Overridepublic void Speak (String str) {System.out.println ("M An:speak "+" ("+ str +") ");} *///error, with @Override, then @Override the following method must be a method override, or compile with an error @overridepublic void speak (int i) {System.out.println ("Man: Speak "+" ("+ i +") ");}}
Package Com.example;public class Test{public static void Main (string[] args) {mans m = new Man (); M.speak (10);}}
Running Result: Man:speak (10)

[Back to top]


Vi. Inheriting abstract classes

1) When inheriting an abstract class, if there is an abstract method in the parent class, then the subclass must all override the abstract method in the parent class

Package Com.example;public abstract class Person{public abstract void P1 ();//abstract method public abstract void P2 ();p ublic void P 3 () {System.out.println ("person:p3 ()");} public void P4 () {System.out.println ("PERSON:P4 ()");}}
Package Com.example;public class Man extends person{@Overridepublic void P1 () {} @Overridepublic void P2 () {}}

[Back to top]


Vii. Final Keywords

1) A class that is decorated by the final keyword cannot be inherited, for example: Public final class person{}

2) In an inheritance relationship, if the method of the parent class is decorated with the final keyword, the method cannot be overridden by the quilt class


[Back to top]


Resources:

The 4th edition of Java programming ideas


end~

Java notes--inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.