一个奇怪的事情发生在人身上

时间:2011-06-16 23:07:25

标签: java oop inheritance subclass superclass

在以下java代码中

public class Person {
    int age = 18;
}

class Student extends Person {
    public Student() {
        this.age = 22;
    }

    public static void main(String[] args) {
        Student student = new Student();
        student.doSomthing();
    }

    void doSomthing() {
        System.out.println(this.age);
        System.out.println(super.age);// Here is something weird, at least for me till rightNow()
    }
}  

为什么super.age值为22,与子类的年龄值相同,是不是应该是18;
任何帮助表示赞赏 提前谢谢。

8 个答案:

答案 0 :(得分:7)

年龄是超类中的一个领域。在子类的构造函数中,当你说this.age = 22时,你正在更新超类中的实例变量。

尝试以下方法......我没有方便的编译器,但我认为它可能会做你期望的。

public class Person {
    int age = 18;
}

class Student extends Person {

    int age; // Hides the super variable

    public Student() {
        this.age = 22;
    }

    public static void main(String[] args) {
        Student student = new Student();
        student.doSomthing();
    }

    void doSomthing() {
        System.out.println(this.age);
        System.out.println(super.age);
    }
}  

答案 1 :(得分:4)

这表现得像你期望的那样。你还没有宣布学生的“年龄”成员,所以this.age自然地引用了超类中定义的“年龄”。

下面的代码将提供您期望的行为(尽管像这样的阴影变量通常是一个非常糟糕的主意)。

public static class Person {
    int age = 18;
}

public static class Student extends Person {
    int age = 18;

    public Student() {
        this.age = 22;
    }

    void doSomthing() {
        System.out.println(this.age);
        System.out.println(super.age);
    }
}

答案 2 :(得分:2)

不,这是正确的。在构造函数中,您将超越超类的年龄。你可以改为做这样的事情:

public class Person {
    public int getAge() {
        return 18;
    }
}

class Student extends Person {
    public Student() {
    }

    @Override
    public int getAge() {
        return 22;
    }

    public static void main(String[] args) {
        Student student = new Student();
        student.doSomthing();
    }

    void doSomthing() {
        System.out.println(this.getAge()); //22
        System.out.println(super.getAge()); //18
    }
}  

答案 3 :(得分:1)

学生从父母那里继承年龄,所以年龄和超级之间没有区别

答案 4 :(得分:1)

不,发生的事情是正确的。当您创建子类(Student是Person的子类)时,该子类将继承超类中的所有字段(变量)。但是,只有一组变量:年龄只有一个值,即使它是继承的。换句话说,当一个类继承一个字段时,它不会创建一个新的副本 - 每个学生只有一个副本。

答案 5 :(得分:1)

在这个源代码中,thissuper是相同的实例变量,因为你在超类中定义它并在子类中继承。

当你创建学生时,你将它初始化为22,就是这样。

答案 6 :(得分:1)

没什么奇怪的,它的行为正确。类Student没有私有变量age,它会覆盖父变量。

答案 7 :(得分:0)

您在age班级中设置了Student,但父级是声明age的父级,并且他们共享同一个变量 - 因此,修改该值是有意义的。然而,Overriden方法会有所不同。

相关问题