Dark Horse Programmer--java Foundation--Relive Java inheritance and rewriting

Source: Internet
Author: User
Tags joins

--java Training, Android training, iOS training,. NET training look forward to sharing with you! ——

Inheritance and Rewriting (extends&override) 1. Inheritance 1.1. The process of generalization

In the previous case, the T class and J classes are defined, and through analysis, there are a lot of duplicate code in these two classes, like the Cells property, the Print method, the drop method, the MoveLeft method, the MoveRight method, are present in these two classes, and the implementation is basically the same , the principle of code reuse can be implemented using inheritance.
First, the Tetromino class of the class T and J classes are constructed, and the public (T class and J class public) information is stored in the parent class, and the class T and J inherit the Tetromino parent class. At this point, the child class can share the data of the parent class. This process is the generalization process.

1.2. Extends keywords

Use inheritance to implement code reuse, in the Java language, you need to implement class inheritance through the extends keyword. When inheritance is complete, subclasses (sub Class) can inherit member variables and member methods of the parent class (Super Class), and subclasses can also define their own member variables and member methods. By then, the subclass will have members of the parent class and members of this class.
It is important to note that the Java language does not support multiple inheritance, that is, a class can inherit only one parent class, but a parent class may have multiple subclasses. Look at the following code:

Publicclass Tetromino {cell[] Cells;publictetromino () {cells =Newcell[4];} Public void Drop(){//Same as written T class} Public void MoveLeft(){//Same as written T class} Public void MoveRight(){//Same as written T class} Public void Print(){//Same as written T class}}publicclass Tetrominot extends Tetromino {publictetrominot (intRowintCol) {cells[0]=newcell (Row, col); cells[1]=newcell (Row, col +1); cells[2]=newcell (Row, col +2); cells[3]=newcell (Row +1, col +1);}}

As shown in the code description: Declare the parent class Tetromino, where the public information is placed, including the cell[] declaration, the Drop () method, the MoveLeft () method, the MoveRight () method, and the print () method. Declares the parameterless constructor and instantiates the member variable cell array. Declares that the subclass Tetrominot inherits Tetromino, declares a parameter constructor, passes the line row row, and columns the col parameter to initialize the T-array element.
In the main method, you declare a T-type object, that is, you can construct a T-type object:
TetrominoT t =newTetrominoT(1,1);
The above code, when creating the subclass object, called the subclass of the parameter constructor for the initialization of data, imagine, the parent class Tetromino the parameterless constructor is executed? By analysis, it is certain that the parameterless constructor of the parent class is executed. The constructor for the parent class is not declared in the program, so how is it executed?

1.3. Construction methods in inheritance

The non-parametric construction method of the parent class is executed because Java stipulates that the subclass must first construct the parent class before it is constructed.
In fact, the constructor of a subclass must be called by the Super keyword to invoke the constructor of the parent class, so that proper initialization can be guaranteed to inherit from the member variables of the parent class.
But looking at the code in the previous case, there is no super call to the parent class constructor, because if the constructor of the parent class is not called in the constructor of the subclass, the Java compiler automatically joins the call to the parent class without a reference to the construction method. Take a look at the following code to illustrate the use of the Super keyword:

publicTetrominoT(intint col){super();    cells[0]=newCell(row, col);    cells[1]=newCell(row, col +1);    ……    }

The above code, super (), automatically joins the compiler, and the Super keyword must be in the first row of the subclass construction method, or there will be a compilation error.
Another point to note is that if the parent class does not provide an argument-free constructor, a compilation error occurs. Take a look at the following example:

class Foo {//父类    int value;Foo(int value){this.value = value;}}class Goo extends Foo {//子类    int num;Goo(int num){this.num = num;}}

Parsing the above code, in the subclass construction method does not write super Call the parent class constructor method, the compiler will add super () by default to call the parent class's parameterless construction method, but the parent class does not define the parameterless constructor method, so a compilation error occurs.
For the above problem, there can be two solutions, one is to add an parameterless constructor in the parent class, and scenario two is to show the constructor method (often used) that calls the parent class in the subclass construction method, so that the member variables of the parent class are initialized, see the following code:

class Goo extends Foo {    int num;Goo(intint num){super(value);this.num = num}}

As the code above, the constructor of the parent class is called in the subclass, and the value member variable that inherits from the parent class is initialized and compiled correctly.

1.4. A reference to the parent class object to the child class

An object of a subclass can be styled as the type of the parent class. That is, a reference that defines a parent type can point to an object of a subclass. See the code below:

 class Foo {    intValue Public voidF () {...} Foo (intValue) { This. value = value;}} class Goo extends Foo {    intNum Public voidG () {...} Goo (intValueintNUM) {Super(value); This. num = num}} class Test{PublicstaticvoidMain (string[] args) {Foo obj =newgoo ( -,3);}}

The above code, in the main method, declares a reference to the parent type to point to the object of the subtype. However, a reference to a parent class can only access the members defined by the parent class, not the part that the child class extends. Look at the following code:

 class Foo {    intValue Public voidF () {...} ... ... ...} class Goo extends Foo {    intNum Public voidG () {...} ... ... ...} class Test{PublicstaticvoidMain (string[] args) {Foo obj =newgoo ( -,3); obj.value= $; Obj.f (); obj.num =5; Obj.g ();}}

Parsing the above code, in the main method, declares that the reference to the parent type points to the object of the child class, and then accesses the member variable value of the parent class and method F that calls the parent class to compile normally. However, a compilation error occurs when you access the NUM variable and the G method through the obj reference. That is because, when a parent type reference is directed to a subclass object, the Java compiler checks whether the called method matches based on the type of the reference (Foo), not the type of the object (Goo).

2. Rewrite 2.1. Override of Method

The following increases the requirement to print the grid coordinates before outputting the graphic, which is called the print () method. To implement this requirement, it is simple to call the print () method directly with the parent type reference, because the print () method is defined in the parent class, so you can call this method directly.
Now the demand continues to increase, requiring that different graphic types enter the appropriate statements before printing the output, for example: After the Tetrominot object calls the print () method, increase the output "I am a T", after the Tetrominoj object calls the print () method, increase the output "I am a J ”。 Because the print () method is now defined in the parent class, only one version, whether it is a T-class object or a J-class object invocation, will output the same data, so it is now impossible to output different results for different objects. To implement this requirement, you need to introduce a concept called method rewriting.
In the Java language, subclasses can override (overwrite) methods that inherit from the parent class, that is, the method name and the parameter list are the same as the methods of the parent class, but the methods are implemented differently.
When a subclass overrides a method of a parent class, the overridden method is called (whether it is called through a reference to a subclass or a reference to a parent class), and the overridden version of the subclass is run. Look at the following example:

class  foo  { public  void  f () {System.out.println ( Span class= "hljs-string" > "FOO.F ()" );}} class  goo  extends   foo  { public  void  f () {System.out.println ( "GOO.F ()" );}} class  test  { Publicstatic void  main (string[] args) {Goo obj1 =newgoo (); obj1.f (); Foo obj2 =newgoo (); obj2.f ();}}  

The parsing code concludes that the output is all "goo.f ()" Because it is a Goo object, so whether it is a reference to a subclass or a reference to a parent class, the final run is the rewritten version of the subclass.

2.2. Using the Super keyword in overrides

In a subclass-overridden method, you can invoke the version of the parent class with the Super keyword, as shown in the following code:

class  foo  { public  void  f () {System.out.println ( Span class= "hljs-string" > "FOO.F ()" );}} class  goo  extends   foo  { public         void  f () {super . F (); System.out.println ( "GOO.F ()" );}} class  test  { Publicstatic void  main (string[] args) {Foo obj2 =newgoo (); obj2.f ();}}  

In the above code, SUPER.F () can call the F () method of the parent class Foo, which outputs the result: FOO.F () goo.f (). Such a syntax is typically used to extend the functionality of a subclass's overriding methods on the basis of the parent class method.

2.3. The difference between overrides and overloads

Overloading and rewriting are completely different syntax phenomena, the differences are as follows:
Overloading: A method that defines multiple methods with the same name but different parameter lists in a class, and determines which method to bind, depending on the number and type of arguments, at compile time.
Rewrite: Refers to a method defined in a subclass that is exactly the same as the parent class, and calls different methods depending on the type of the object (not the reference type) when the program is run.
Analyze the output of the following code:

 class Super { Public voidF () {System.out.println ("Super.f ()");}} class Sub extends Super { Public voidF () {System.out.println ("Sub.f ()");}} class Goo { Public voidG (Super obj) {System.out.println ("G (Super)"); Obj.f ();} Public voidG (Sub obj) {System.out.println ("G (Sub)"); Obj.f ();}} class Test{PublicstaticvoidMain (string[] args) {Super obj =newsub (); Goo Goo =newgoo (); goo.g (obj);}}

Analysis of the above code, the output is: g(Super) sub.f() .
First, overloading follows the so-called "compile-time binding," which determines which method should be called at compile time based on the type of the parameter variable, because the variable obj is a super type reference, so the Goo G (super) is called, and the G (Super) is output first.
Overrides follow so-called "run-time bindings" that invoke methods at run time, based on the type of the actual object that the reference variable points to, because obj actually points to the object of the sub-class sub, so the subclass-overridden F method is called, Sub.f ().

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dark Horse Programmer--java Foundation--Relive Java inheritance and rewriting

Related Article

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.