// Parent Class
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setAge(int age) { this.age =age; }
public int getAge() { return age; }
}
// Subclasses
class Student extends Person {
private int id;
private String major;
public Student(String name, int id) {
super(name, super.getAge()); // error!
this.id = id;
}
// Accessor, Setter, corresponding to the variable
// ... omission
}
You're not supposed to change the constructor or parameters in this code When calling a constructor of a higher class in a lower class, there is an error
Cannot refer to 'this' nor 'super' while explicitly invoking a constructor
I got this error.
Is it possible to call the constructor written in the parent class without adding other parameters to the constructor in the lower class? I don't think the problem is wrong(Crying)
java constructor inheritance
super() calls the constructor of the parent class.
super refers to objects in the parent class.
This error occurs because the object's method is called (referenced) before it is even created.
This means that while creating an object for the parent class Person, it occurs by referring to the Person object. You can put the int value instead of super.getAge().
To understand the above accurately, we need to understand the constructor. Replace this with This article . It's an old article, but it's well explained. I hope it helps.
© 2024 OneMinuteCode. All rights reserved.