代码: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();一定要写在开头