Super is more common in Android, and I don’t understand it without Java foundation, so I have time to learn it.
Using super in Java classes to reference the components of the base class is relatively simple, and the example is as follows:
class FatherClass{ public int value; public void f(){ value=100; System.out.println ("FatherClass.value:"+value); } } class ChildClass extends FatherClass{ public int value; public void f(){ super.f(); value=200; System.out.println ("ChildClass.value:"+value); System.out.println(value); System.out.println(super.value); } } public class test1 { public static void main(String[] args){ ChildClass cc=new ChildClass(); cc.f(); } } The final output is:
FatherClass.value:100ChildClass.value:200200100
In addition, super is also used in the inheritance construction, the specific rules are as follows:
1. The construction method of its base class must be called during the construction process of a subclass.
2. Subclasses can use super(argument_list) to call the base class's constructor method in their own constructor.
3. If the constructor of the subclass is not displayed in the constructor of the base class, the system calls the parameterless constructor of the base class by default.
4. If the subclass constructor does not show the call to the base class constructor, and the base class does not have a constructor without parameters, a compilation error occurs.
The examples are as follows: (It is best to experiment with it yourself here)
class SuperClass{ private int n; SuperClass(){ System.out.println("Call SuperClass()"); } SuperClass(int n){ System.out.println("Call SuperClass("+n+")"); } } class SubClass extends SuperClass{ private int n; SubClass(int n){ //When superclass construction method is not written in the subclass construction method, the system defaults to call the parent class without parameters//It is equivalent to writing the following here: //super(); System.out.println("Call SuberClass("+n+")"); this.n=n; } SubClass(){ super(300); //The parent class constructor must be called during the subclass construction process, and super must be written in the first sentence (there is a father first and then the son) System.out.println("Call SubClass()"); } } public class test2 { public static void main(String[] args){ SubClass sc1=new SubClass(); SubClass sc2=new SubClass(400); } } The final result is:
Call SuperClass(300) Call SubClass() Call SuperClass() Call SubClass(400)
The above is all about this article, I hope it will be helpful to everyone's learning.