super() (1)

Java 只支持单继承,不支持多继承
单继承就是一个类只能由一个父类;多继承就是一个类可以有多个父类。
子类可以继承父类所有的成员变量和成员方法,但子类永远无法继承父类的构造器(Constructor)。在子类构造方法中可以使用语句 Super(参数列表)调用父类的构造方法。
So, let’s see: subclass can’t inherit Superclass’ constructor.
Assume we have below:
——————–
class A {
private int i,j,k;
public A() {
这里给 i,j,k 赋值
}
}
class B extends A
{

}
——————–
因为 B 无法继承父类 A 的Constructor,所以就无法利用构造器给 i/j/k进行方便的赋值。那么怎么办呢?there are 2 ways:
1. 笨的方法: 在子类中一个一个给所有变量赋值。
2. 使用 Super 方法。
我们先来看笨的方法
————-TestSuper.java———-
package ch.allenstudy.newway03;
public class TestSuper {
public static void main(String[] args)
{
B bb = new B(11,22,33);
}
}
class A
{
public int i;
public int j;
public A()
{
}
public A(int i, int j)
{
this.i = i;
this.j = j;
}
}
class B extends A
{
public int k;
public B()
{
}
public B(int i, int j, int k) //Why here we don’t only declare public B(int k)? because, even we only have a “k” property in B, but we extends from A, this means that we in fact also have another 2 properties — i and j; So we should write 3 parameters in the constructor.
{
this.i = i;
this.j = j;
this.k = k;
//上面我们一个一个的给 i/j/k 赋值。 但是假如A有100个属性,这种方法就需要赋值100次,非常麻烦。

}
}
———————————–
聪明的方法: 使用 Super
Let’s see a sample:
———–TestSuper.java———-
package ch.allenstudy.newway03;
public class TestSuper {
public static void main(String[] args)
{
B bb = new B(11,22,33);
System.out.printf(“%d %d %d\n”, bb.i, bb.j, bb.k);
}
}
class A
{
public int i;
public int j;
public A()
{
}
public A(int i, int j)
{
this.i = i;
this.j = j;
}
}
class B extends A
{
public int k;
public B()
{
}
public B(int i, int j, int k)
{
super (1,2); //use “super” to assign value to i and j. 同时还要注意: super 要放在构造函数中,而且是第一个语句。
this.k = k;
}
}
———-Result———
1 2 33

正如上面说的:要放在构造函数中,而且是第一个语句。
你不要把 super() 放在普通方法中。 下面这个就是错的。
class A {
public int i;
}

class B extends A {
public int j;
public void f(int i)
{
super(i); //Error: super被放在了方法 f()中
}
}

原文地址:https://www.cnblogs.com/backpacker/p/2271563.html