I have investigated polymorphism again, so I will summarize it. This time I want to deepen and understand super ()
** Target **
--Someone who writes Java somehow
** Conclusion **
I will try it with a concrete example
Person.java
public class Person {
Person() {
System.out.println("I am a human." + );
}
}
Student.java
public class Student extends Person {
Student() {
System.out.println("I am a student.");
}
}
Main.java
public class Main {
public static void main() {
new Student();
}
}
I am a human.
I am a student.
The constructor of the Student class does not have a description to output "Human.", But it is displayed. In other words, the constructor of the Student class that inherits Person
Person.java
public class Student extends Person {
Student() {
super();
System.out.println("I am a student.");
}
}
It looks like this.
(It's not actually done, but if you write it explicitly, it looks like this. When you create an instance of an inherited class, the constructor of the parent class is called automatically)
This super () is the constructor of the parent class.
Then add the arguments to the constructor of the parent class
Person.java
public class Person {
private String name;
Person(String name) {
this.name = name;
System.out.println(name + "is.");
}
}
Main.java
public class Main {
public static void main() {
new Student();
}
}
Yes. There is a compilation error. This is because the constructor of the Person class requires an argument. In such a case, you need to call super () with an argument in the Student class.
Student.java
public class Student extends Person {
Student(String name) {
super(name);
System.out.println("I am a student.");
}
}
Main.java
public class Main {
public static void main() {
new Student("Yamada");
}
}
This is Yamada.
I am a student.
Student inherits from Person, so it also has a name field
Main.java
public class Main {
public static void main() {
Student student = new Student("Yamada");
System.out.println(student.name);
}
}
This is Yamada.
I am a student.
Yamada
Recommended Posts