The more common Java super keyword in Android

  • 2020-04-01 04:35:08
  • OfStack

Super is quite common in android and is not understood without a Java foundation, so I took the time to learn it.

Using super to reference the components of the base class in a Java class is simple, as shown in the following example:


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:100
ChildClass.value:200
200
100

In addition, super is also used in the construction of inheritance. The specific rules are as follows:

1. During the construction of a subclass, the constructor of its base class must be called.

2. A subclass can use super(argument_list) in its constructor to call the constructor of the base class.

3. If there is no constructor shown in the constructor of the subclass to call the constructor of the base class, the system will call the no-parameter constructor of the base class by default.

4. If the subclass constructor is not shown to invoke the base class constructor, and the base class has no parameterless constructor, the compilation fails.

Here's an example :(try it out for 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 super is not written in the constructor of a subclass, the system defaults to calling the constructor of the parent class with no arguments
    //The equivalent is written here:
    //super(); 
     
    System.out.println(" call SuberClass("+n+")"); 
    this.n=n; 
  } 
   
  SubClass(){ 
    super(300); 
    //The parent constructor must be called during subclass construction, and super must be written in the first sentence (first father, then 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 SuberClass(400)

The above is the entire content of this article, I hope to help you with your study.


Related articles: