About the parameterized constructor

About the parameterized constructor

  • If you define a constructor with parameters, the default parameterless structure will be invalid unless you define another parameterless structure yourself
  • The subclass inherits the parent class does not inherit the constructor, but only explicitly or implicitly callIf the constructor of the parent class has parameters, the subclass must call the constructor of the parent class via super as shown in the constructor. If the constructor has no parameters, the system will automatically call the constructor without parameters
public class A{
    
    
	int x;
	public A(){
    
    
		this.x=1;
	}
	public A(int x){
    
    
		this.x=x;
	}
}

public class B extends A{
    
    
	public B(){
    
    }
	public B(int x){
    
    super(x)}
	public static void main(String[] args){
    
    
		B b=new B();
		b.x==1;
		B b2=new B(3);
		b.x==3;
	}
}

If the parent class constructor is not displayed, the parent class no-argument constructor will be automatically called

public class C extends A{
    
    
	public C(){
    
    }
	public C(int x){
    
    }
	public static void main(String[] args){
    
    
		C c=new C(3);
		c.x==1;
	}
}

Guess you like

Origin blog.csdn.net/qq_36976201/article/details/112843398