super的方法

代码:package how;

class A{
	int i,j;
	private int mm=100;
	public A(int i,int j){
		this.i = i;
		this.j = j;
	}
	public A(){
		
	}
}

class B extends A
{
	int k;
	public B(int i,int j,int k){
		super(i,j);
		this.k = k;
	}
}
public class new_start {
	public static void main(String[] args){
		B bb = new B(100,1,2);
		System.out.printf("%d %d %d",bb.i,bb.j,bb.k);
		System.exit(0); 
	}

}


super继承的一些注意的地方:

①super只能写在构造函数的第一条语句中,若在普通的方法函数中构造就会报错。

②错误代码如下:若调用super必须在原来的父类中构造函数有参数才行,否则执行默认的无参数就会报错:
package how;

class A{
	int i,j;
	private int mm=100;
	
	public A(){
		
	}
}

class B extends A
{
	int k;
	public B(int i,int j,int k){
		super(i,j);
		this.k = k;
	}
}
public class new_start {
	public static void main(String[] args){
		B bb = new B(100,1,2);
		System.out.printf("%d %d %d",bb.i,bb.j,bb.k);
		System.exit(0); 
	}

}




package how;

class A{
	int i,j;
	private int mm=100;
	
	public A(){
		
	}
	//public A(int i,int j){
		//this.i = i;
		//this.j = j;
	//}
}

class B extends A
{
	int k;
	public B(int k){
		super();
		//super(i,j);
		this.k = k;
	}
}
public class new_start {
	public static void main(String[] args){
		B bb = new B(2);
		System.out.printf("%d %d %d",bb.i,bb.j,bb.k);
		System.exit(0); 
	}

}


若在构造函数中没有构造,则会默认的加入super(i,j);

	public B(int i,int j,int k){
		//super();
		//super(i,j);
		this.k = k;
	}

重写:函数同名同参同返回值。
不能不是不同的返回类型。


super的其他的调用的方式:
若子类和父类有相同的方法,(相当于子类重写了父类的方法),则要在子类中调用父类的方法时:super.method();一定要写在开头
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值