热门搜索 :
考研考公
您的当前位置:首页正文

Java变量重写的问题

来源:东饰资讯网

Java中父类的同名方法会被子类重写,因此就有了面向对象编程的三大要素之一——多态!但是,如果父类和子类拥有同名属性,那么会产生什么效果呢?下面是一个例子:

public class Person {
    public String name = "father";

    public void printName() {
        System.out.println(this.name);
        System.out.println(this.getClass());
    }
}
public class Student extends Person{
    public String name = "son";
    
    public static void main(String[] args){
        Person s = new Student();
        s.printName();
    }
}

输出结果:

father
class Student

首先Student类由于继承了Person类,实际上它拥有两个属性:super.name 和 name。
调用printName() 方法时,由于printName是父类中的方法,因此这行代码:

System.out.println(this.name);

实际上已经和super.name绑定了,因此会输出father。

而这行代码:

System.out.println(this.getClass());

由于方法重写的特性,因此会输出Student。

总结:Java中不存在变量重写的概念。

Top