1:
public class inheritance {
public static void main(String[] args) {
EmployeeSon son = new EmployeeSon();//建立一个子类对象
son.method();//EmployeeSon里面虽然什么都没有写,但是会继承父类的method()方法。
}
}
class Employee{
int num = 100;//父类的成员变量。
public void method(){
System.out.println("方法执行");
}
}
class EmployeeSon extends Employee{
int num = 200;//本类的成员变量。
@Override//表示覆盖重写。
public void method(){
int num = 300;//局部变量。
System.out.println(num);//局部变量。
System.out.println(this.num);//本类的成员变量。
System.out.println(super.num);//父类的成员变量。
}
}
2:一个继承的小案例。
public class inheritance002 {
public static void main(String[] args){
NewPhone com = new NewPhone();
com.call();
com.send();
com.show();
}
}
//老手机的功能;
class phone{
public void call(){
System.out.println("打电话");
}
public void send(){
System.out.println("发短信");
}
public void show(){
System.out.println("来电显示");
}
}
//更新,定义一个新手机,继承老手机功能,然后添加新功能;
class NewPhone extends phone{
public void show(){
super.show();//把父类的方法拿过来;
//添加自己的新功能。
System.out.println("显示姓名");
System.out.println("显示号码");
}
}
3:继承关系中,父子类构造方法的访问特点。
public class inheritance003 {
public static void main(String[] args) {
zi mon = new zi();
}
}
class fu{
public fu(){
System.out.println("父类构造方法");
}
public fu(int num){
System.out.println("父类有参构造方法");
}
}
//更新,定义一个新手机,继承老手机功能,然后添加新功能;
class zi extends fu{
public zi(){
//super();默认调用父类构造方法;
super(10);//对应那个父类构造函数就调用哪一个。
System.out.println("子类构造方法");
}
}


