Super Keyword: reference the components of the parent class in the subclass object (including the member variables and member methods of the parent class)
Class FatherClass // define the parent class
{
Public int value;
Public void f ()
{
Values = 100;
System. out. println
("FatherClass. value =" + value );
}
}
Class ChildClass extends FatherClass // defines a subclass that inherits the parent class
{
Public int value; // defines a member variable with the same name as the parent class.
Public void F () // override the method F () of the parent class ()
{
Super. F (); // use super/to call the method F () of the parent class in the subclass method ();
Value = 200; // The value belongs to the subclass.
System. out. println ("ChildClass. value =" + value );
System. out. println (value); // print the subclass value.
System. out. println (super. value); // print the value of the parent class
}
}
Public class TestInherit
{
Public static void main (String [] args)
{
ChildClass cc = new ChildClass ();
Cc. f ();
}
}
The code is shown in the memory;
This Keyword:When managing a call to a Java virtual machine, you need to know which object to call, right ?? A class can have multiple objects, the object ABCDEFG. When you call it, you must tell the virtual machine that the method or attribute of object A is to be called. How can I tell a virtual machine ?? Is to pass A reference of object A to the virtual machine, and
This keyword can be used to access this reference. Therefore, we can use the this keyword to access any method or attribute of the current object. (Except static, which is independent of objects)
Package test;
Public class ThisTest {
Private int I = 0;
ThisTest (int I) // The first Constructor
{
This. I = I + 1; // at this time, this indicates referencing the member variable I, not the function parameter I
System. out. println (I );
System. out. println (this. I );
// The two output results fully prove that I and this. I are different!
}
ThisTest (String s) // second Constructor
{
System. out. println ("String constructor:" + s );
}
ThisTest (int I, String s) {// third constructor: an int-type parameter and a String-type parameter
This (s); // this calls the second Constructor
This. I = I ++; // this to reference the member variables of this class
System. out. println ("Int constructor:" + I + "/n" + "String constructor:" + s );
}
Public ThisTest increment (){
This. I ++;
Return this; // The current object is returned, which belongs to (ThisTest)
}
Public static void main (String [] args ){
ThisTest tt0 = new ThisTest (10 );
ThisTest tt1 = new ThisTest ("OK ");
ThisTest tt2 = new ThisTest (20, "OK again! ");
System. out. println (tt0.increment (). increment (). increment (). I );
// Tt0.increment () returns a ThisTest object based on tt0 and I ++,
// Then return the ThisTest object I ++ on the basis of the object returned above!
}
}