继承、重写以及this、super的使用
父类Extend的信息:
public class Extend {
static int age=98;
String hobby;
public Extend(){
System.out.println("Extend无参构造方法");
}
public void say() {
System.out.println("I'm father");
}
public void money(){
System.out.println("I've a lot of money");
}
public void dream(){
System.out.println("I dream I've a son");
}
private void weigth(){//私有方法不能被子类继承和重写
System.out.println("我的体重70kg");
}
public static void familymember(){//声明为static的方法不能被子类重写,但是可以被再次声明
System.out.println("家庭成员有三个人");
}
public final void wife(){//声明为final的方法不能被重写
System.out.println("我的老婆叫李静");
}
}
对父类方法进行重写后左侧会出现一个绿色小三角符号:比如:
子类继承并重写父类方法:
//继承、重写以及this、super的使用
//重写可以抛出异常,但是不能抛出比父类还要大的异常,只可以小,不可以更大,而且不能抛出新的异常;
//重写后的方法的访问权限只能更大,不能更小,比如说父类的方法的访问性是public,子类继承后就不能使用protected;
//父类不能被继承的方法都不能对其进行重写;
//构造方法可以被继承,但是不能被重写;
public class Extendone extends Extend {
String hobby;
int age;
public Extendone(){
System.out.println("Extendone的无参构造方法");
}
// 对父类的money()方法进行重写
public void money() {
System.out
.println("I've got no money,but my father have a lot of money!");
}
public void say() {
System.out.println("I've a father.");
}
public String say(String people) {// 形参列表和返回值与父类的不同,所以不是重写
return "三个" + people;
}
public static void familymember() {//再次声明familymember()方法
System.out.println("我是儿子,我现在的家庭成员是四个人");
}
public void superThisDemo() {
// this用于调用自身的方法或者成员变量
// super用于调用父类的方法或者成员变量
this.say();// 调用自身的say()方法
super.say();// 调用父类的say()方法
super.money();// 调用父类的money()方法
this.money();// 调用自身的money()方法
System.out.println("父类的年纪是:"+super.age+"岁");
this.age=22;
System.out.println("子类的年纪是:"+this.age);
super.hobby="下棋、饮酒";
System.out.println("父类的爱好是:"+super.hobby);
this.hobby="踢球、打游戏";
System.out.println("子类的爱好是:"+this.hobby);
super.familymember();
this.familymember();
}
public static void main(String[] args) {
Extendone one = new Extendone();
one.money();
one.say();
one.dream();
String a = one.say("奇怪的人");
System.out.println(a);
System.out.println("-------super/this关键字的使用--------");
one.superThisDemo();
}
}
/*
重载与重写的区别:
方法的重载在同一个类中的方法名相同,参数数量不同或者数量相同而参数类型和次序不同;
方法的重写是通过继承关系达成的。
子类中的方法和父类的方法的名字、参数个数、类型和返回值都一样,就说明这个方法时子类对父类方法的重写,static方法除外,
static方法只能在子类中被再次声明,而不能被子类进行重写;
方法的重载是类的多态性的一个表现,而重写是子类与父类的一个多态性的表现;
*/
结果展示: