Prepare a parent class that explicitly provides a no-argument constructor
package charactor;
public class hero implements AD{
String name;
int hp;
float movespeed;
int armor;
public void physicattack() {
System.out.println("物理攻击");
}
public void die() {
}
public void kill(hero i) {
i.die();
}
public static void battlewin() {
System.out.println("战斗胜利");
}
public void hero(item a) {
System.out.println("hero use item");
a.effect();
}
public static void main(String args[]) {
new hero();
}
}
Instantiate the subclass, the constructor of the parent class will be called
Instantiate an ADHero(), its construction method will be called, and the construction method of the
parent class will also be called
and the parent class construction method will be called first
. The subclass construction method will call the parent class's no-parameter construction method by default
package charactor;
public class adhero extends hero implements mortal,AD{
public adhero() {
System.out.println("我是adhero的构造方法");
}
public static void main(String args[]){
new adhero();
}
}
The parent class explicitly provides two construction methods
They are the construction method with no parameters and the construction method with one parameter.
package charactor;
public class hero implements AD{
String name;
int hp;
float movespeed;
int armor;
public hero() {
System.out.println("我是hero的构造方法");
}
public hero(String name) {
System.out.println("hero 的一个又参数的构造方法");
this.name = name;
}
The subclass explicitly calls the parent class's construction method with parameters
package charactor;
public class adhero extends hero implements mortal,AD{
public void physicattack(){
System.out.println("进行物理攻击");
}
public adhero() {
System.out.println("我是adhero的构造方法");
}
public static void main(String args[]){
new adhero();
new adhero("德玛西亚啦啦啦");
}
public adhero(String name) {
super(name);
System.out.println("这是一个带参数的构造方法");
}
Call parent attribute
Call the parent class's moveSpeed attribute
ADHero through super also provides the attribute moveSpeed
public int movespeed1() {
return this.movespeed1;
}
public int movespeed() {
return super.movespeed;
}
Call parent method
ADHero rewrites the useItem method, and calls the useItem method of the parent class through super in useItem
public void useitem(item a) {
System.out.println("重写这个useitem方法");
super.useitem(a);
}
to sum up:
super can be used as a reference to the parent class
Exercise-super⭐⭐⭐The
parent class Hero provides a parameterized construction method,
but does not provide a parameterless construction method.
What should the subclass do?
//父类,hero类
public void useitem() {
System.out.println("hero use item");
item a = new item();
a.effect();
}
//子类,adhero类
public void useitem() {
System.out.println("重写这个useitem方法");
super.useitem();
}