Java reuse class learning Summary

Source: Internet
Author: User
Document directory
  • Downward Transformation

1. Inheritance syntax

When creating a class, you can either specify the class it inherits, such as a extends B. Otherwise, it will inherit the root class Object implicitly.

As for the specific inheritance syntax, I will not go into details here. Here I want to write about the permissions in inheritance:

Taking a extends B as an example, the method in B must be public, which is very important. Remember, if no permission modifier is added, the default access permission of a member is package access permission, that is, all the Members in the package can access its method.

However, the members in other packages, such as C extends B, can only access the public members in B.

2. initialize the base class (parent class, superclass)

The first line of the constructor () with or without parameters) of each subclass calls the base class parameter-free constructor by default.

Case 1: No matter whether super () is written in the first line of the constructor of subclass A (if not written), the system will first call Super ().

 

Case 2: If super (corresponding parameter) is written in the first line of constructor of subclass A, corresponding constructor of base class B is called; if super (corresponding parameter) is not specified, the system will first call Super ().

 

Case 3: the first line of the constructor of subclass A must be written with super (corresponding parameter). Otherwise, the compilation will fail because you do not write super (corresponding parameter, the system calls super () first, but there is no constructor without parameters in the base class.

 

 

Summary: calling the base class (parent class) constructor must be the first thing you need to do in the export class (subclass) constructor.

 

In addition, when new A () is used, super () is called by default, which means Class B is initialized first in the initialization order (as shown in my related blog.

For example:

Class component1 {
Public component1 (string s) {system. Out. println ("component1 ");}
}
 
Class component2 {
Public component2 (string s) {system. Out. println ("component2 ");}
}
 
Class component3 {
Public component3 (string s) {system. Out. println ("component3 ");}
}
 
Class root {
Component1 C1 = new component1 ("Q ");
Component2 C2 = new component2 ("");
Component3 C3 = new component3 ("Z ");
Public root (string s) {system. Out. println ("root ");}
}
 
Class stem extends root {
Component1 C1 = new component1 ("W ");
Component2 C2 = new component2 ("S ");
// Component3 C3 = new component3 ();

Public stem (string s ){
Super (s );
System. Out. println ("stem ");}
}
 
Public class test {
Public static void main (string ARGs []) {
New stem ("X ");
}
}

Result:


3. Protected keyword

In actual projects, you often want to hide some things in the world as much as possible, but still allow export classes or other classes located in the same package, but it is accessible. (Protected also provides package access permissions)


4. Upward Transformation (interesting)

The most important aspect of inheritance technology is to express the relationship between the new class and the base class. This relationship can be summarized using the phrase "the new class is a type of the existing class.

For example:

Class instrument {
Void play () {system. Out. println ("play ");
}
Static void tune (instrument I) {I. Play ();
}
}
Public class AB extends instrument {
Public static void main (string ARGs []) {
AB AB = new AB ();
Instrument. Tune (AB );
}
}

Result: Play

In this example, the tune () method can be referenced by instrument, but in the AB. Main method, the parameter passed to tune () is a reference of AB. This means that we can accurately define AB objects as a type of instruments. In tune (), the program code can work for instruments and all their export classes. This kind of action that converts AB references to instrument references is called upward transformation.

For example, a sparrow is a type of bird (a subclass of birds), and a bird is a type of animal (a subclass of animals ). We often say this in reality: Sparrow is a bird. These two statements are actually called "upward transformation". In other words, sub-classes are transformed into parent classes. Let's look at the following code:

Package A. B;

Public Class {

Public void A1 (){

System. Out. println ("superclass ");

}

}

Subclass B of:

Package A. B;

Public Class B extends {

Public void A1 (){

System. Out. println ("childrenclass"); // overwrite the parent class Method

}

Public void B1 () {}// Class B defines its own New Method

}

Class C:

Package A. B;

Public class c {

Public static void main (string [] ARGs ){

A A = new B (); // upward Transformation

A. A1 ();

}

}

If C is run, is the output superclass or childrenclass? It is not the superclass you expected, but childrenclass. This is because a actually points to a subclass object. Of course, you don't have to worry about it. the Java Virtual Machine automatically and accurately identifies the specific method to call. However, due to the upward transformation, the object will lose methods different from the parent class, such as B1 ().

Package A. B;

Public Class {

Public void A1 (){

System. Out. println ("superclass ");

}

}

Subclass B of:

Package A. B;

Public Class B extends {

// Public void A1 (){

// System. Out. println ("childrenclass"); // overwrite the parent class Method

//}

Public void B1 () {}// Class B defines its own New Method

}

Class C:

Package A. B;

Public class c {

Public static void main (string [] ARGs ){

A A = new B (); // upward Transformation

A. A1 ();

}

}

If you modify the code like this, the result is superclasss. (First look for the method in the subclass. If not, the base class is called .)

Some may ask: Isn't that an option? We can write like this:

B A = new B ();

A. A1 ();

Indeed! However, the abstract programming features are lost and the scalability is reduced. In fact, more than that, the upward transformation can also reduce the programming workload. Let's look at the following monitor:

Package A. B;

Public class monitor {

Public void displaytext (){}

Public void displaygraphics (){}

}

LCD monitor is a subclass of monitor:

Package A. B;

Public class lcdmonitor extends monitor {

Public void displaytext (){

System. Out. println ("LCD display text ");

}

Public void displaygraphics (){

System. Out. println ("LCD display graphics ");

}

}

The crtmonitor type of the cathode ray tube display is naturally a subclass of monitor:

Package A. B;

Public class crtmonitor extends monitor {

Public void displaytext (){

System. Out. println ("CRT display text ");

}

Public void displaygraphics (){

System. Out. println ("CRT display graphics ");

}

}

Plasmamonitor is also a subclass of monitor:

Package A. B;

Public class plasmamonitor extends monitor {

Public void displaytext (){

System. Out. println ("plasma display text ");

}

Public void displaygraphics (){

System. Out. println ("plasma display graphics ");

}

}

Now there is a mymonitor class. Assuming there is no upward transformation, the mymonitor class code is as follows:

Package A. B;

Public class mymonitor {

Public static void main (string [] ARGs ){

Run (New lcdmonitor ());

Run (New crtmonitor ());

Run (New plasmamonitor ());

}

Public static void run (lcdmonitor Monitor ){

Monitor. displaytext ();

Monitor. displaygraphics ();

}

Public static void run (crtmonitor Monitor ){

Monitor. displaytext ();

Monitor. displaygraphics ();

}

Public static void run (plasmamonitor Monitor ){

Monitor. displaytext ();

Monitor. displaygraphics ();

}

}

You may have realized that the above Code has a lot of repeated code and is not easy to maintain. With the upward transformation, the code can be simpler:

Package A. B;

Public class mymonitor {

Public static void main (string [] ARGs ){

Run (New lcdmonitor (); // upward Transformation

Run (New crtmonitor (); // upward transition

Run (New plasmamonitor (); // upward Transformation

}

Public static void run (monitor) {// The parent class instance is used as the parameter

Monitor. displaytext ();

Monitor. displaygraphics ();

}

}

Downward Transformation

The transformation from a subclass to a parent class is an upward transformation. In other words, the transformation from a parent class to a subclass is a downward transformation. However, the downward transformation may bring about some problems: we can say that the sparrow is a bird, but it cannot be said that the bird is a sparrow. Let's look at the following example:

Class:

Package A. B;

Public Class {

Void amthod (){

System. Out. println ("A method ");

}

}

Subclass B of:

Package A. B;

Public Class B extends {

Void bmethod1 (){

System. Out. println ("B method 1 ");

}

Void bmethod2 (){

System. Out. println ("B method 2 ");

}

}

Class C:

Package A. B;

Public class c {

Public static void main (string [] ARGs ){

A a1 = new B (); // upward Transformation

A1.amthod (); // call the parent class amthod (), A1 loss of Class B Methods bmethod1 (), bmethod2 ()

B b1 = (B) A1; // downward transformation, no compilation errors, no running errors

B1.amthod (); // call the parent class A Method

B1.bmethod1 (); // call class B Methods

B1.bmethod2 (); // call class B Methods

A a2 = new ();

B b2 = (B) A2; // downward transformation, no compilation error, and errors will occur during runtime

B2.amthod ();

B2.bmethod1 ();

B2.bmethod2 ();

}

}

From the code above, we can conclude that forced conversion is required for downward transformation. Run the C program and the console will output:

Exception in thread "Main" Java. Lang. classcastexception: A. B. A cannot be cast to A. B. B
A. B. C. Main (C. Java: 14)

A Method

A Method

B method 1

B method 2

In fact, the comments after the downward transformation code of the simhei section have prompted you to encounter a runtime error. Why can the previous sentence Transform code down, but the other sentence code fails? This is because A1 points to an object of subclass B, so Instance Object B1 of subclass B can also point to A1. A2 is a parent class object, and B2 of the subclass object cannot point to A2 of the parent class object. So how to avoid the exception of classcastexception during the execution of the downward transformation? You can use the instanceof that has been learned in section 5.7.7. Let's modify the C class code:

A a2 = new ();

If (A2 instanceof B) {// test whether A2 is a B-type instance and return boolean data

B b2 = (B) A2;

B2.amthod ();

B2.bmethod1 ();

B2.bmethod2 ();

}

After such processing, you don't have to worry about classcastexception exceptions during type conversion.


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.