有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

爪哇人身上发生了奇怪的事情

在下面的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()
    }
}  

为什么是超级。年龄值是22,与子类的年龄值相同,是不是应该是18
感谢您的帮助
提前谢谢


共 (6) 个答案

  1. # 1 楼答案

    这是你所期望的。您尚未声明学生的“年龄”成员,因此,请执行此操作。age自然引用超类中定义的“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 楼答案

    年龄是超级阶级的一个领域。在子类的构造函数中,当您这样说时。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);
        }
    }  
    
  3. # 3 楼答案

    不,那是正确的。在构造函数中,您正在重写超类的年龄。您可以这样做:

    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
        }
    }  
    
  4. # 4 楼答案

    在这个源代码中,thissuper是同一个实例变量,因为您在子类中继承的超类中定义了它

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

  5. # 5 楼答案

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

  6. # 6 楼答案

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