直接上代码好吧
//在Mainclass.java文件中
//定义个Parent类作为父类
class Parent{
String name;
//构造方法
public Parent(String n){
this.name = n;
}
//成员方法work
public void work(){
System.out.println("Parent的工作是工作赚钱");
}
//
public void live(){
System.out.println("生活天天开心");
}
}
//定义个子类Son继承Parent类
class Son extends Parent{
//子类构造方法
public Son(String sn){
//调用父类构造方法
super(sn);
}
//重写父类方法
public void work(){
System.out.println("Son的工作是努力学习");
}
public void son_live(){
//调用父类方法
super.live();
System.out.print("还要替parent分忧");
}
}
//主类
public class Mainclass{
public static void main(String[] args){
Parent p = new Parent("小头爸爸");
Son s = new Son("小头儿子");
System.out.println(p.name);
System.out.println(s.name);
p.work();
s.work();
p.live();
s.live();
s.son_live();
}
}
看完上面的代码,已经对类继承有了个了解,现在来做个总结回顾下过程:
- 类继承用的关键字是extends
- 在其子类中,使用super.funcname()方式调用父类的方法(执行父类方法中的方法体);使用super(param)方式调用父类的构造方法(执行其构造方法中的方法体)
- 父类如果有构造方法,其子类必须也要定义构造方法
- 在类的结构上,子类继承了父类的结构,还可做出扩展(如定义新方法、新成员变量)