I know this question has been already asked here, but I fail to understand the "Why" part.
Let us take the following example:
public class First {
First() {
System.out.println(super.getClass());
}
}
public class Second extends First {
Second() {
System.out.println(super.getClass());
}
}
public class Third extends Second {
Third() {
System.out.println(super.getClass());
}
}
When I instantiate an Object of type Third:
public class Main {
public static void main(String[] args) {
Third third = new Third();
}
}
The output is:
class Third
class Third
class Third
And what I expected was (Thinking that super.getClass() should return the name of parent class):
class java.lang.Object
class First
class Second
Which shows that I don't understand how does Inheritance actually work in Java. Kindly help me in getting the right concept in my head.
EDIT
My actual intention was to understand how inheritance actually works (which has been explained very well by Jeff), instead of getting the expected output.
This doubt arose when I was trying to the understand why the following code worked (More specifically, why does super.equals(point3d) worked as it has been passed an object of type Point3D)
public class Main {
public static void main(String[] args) {
Point3D p1 = new Point3D(1, 2, 3);
Point3D p2 = new Point3D(1, 2, 3);
System.out.println(p1.equals(p2)); // Output: true
}
}
public class Point {
private int x;
private int y;
public Point() {
this.x = 0;
this.y = 0;
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object object) {
if (object != null && object.getClass() == this.getClass()) {
Point point = (Point) object;
return point.x == this.x && point.y == this.y;
} else {
return false;
}
}
}
public class Point3D extends Point {
private int z;
public Point3D() {
this.z = 0;
}
public Point3D(int x, int y, int z) {
super(x, y);
this.z = z;
}
@Override
public boolean equals(Object object) {
if (object != null && object.getClass() == this.getClass()) {
Point3D point3D = (Point3D) object;
return super.equals(point3D) && point3D.z == this.z; // Had doubt here
} else {
return false;
}
}
}