关于带参构造函数

关于带参构造函数

  • 若自己定义了一个带参的构造函数,那么默认的无参构造就会失效,除非自己再定义一个无参构造
  • 子类继承父类是不继承构造函数的,只是显示或者隐式的调用,若父类构造器带有参数,子类必须再构造器中显示的通过super调用父类构造器,若构造器没有参数,则系统自动调用无参构造器
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;
	}
}

如果不显示调用父类构造器,会自动调用父类无参构造器

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;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_36976201/article/details/112843398