Java继承关系的理解

首先有一个基类 Thing

public class Thing {

    public Thing() {
        System.out.println("Everything begins here!");
    }
}

然后有个子类命名为Shape(形状)继承Thing

public class Shape extends Thing {
    public String name = "Shape";
    private static String sname = "S-Shape";

    public Shape() {
        System.out.println("Here is constructor of Shape!");
    }

    public void getName() {
        System.out.println("This is getName of Shape! ");
    }

    public static void getSname() {
        System.out.println("Here is static getName of Shape");
    }
}

然后有个子类命名为Circle(圆)继承Shape

public class Circle extends Shape {

    public String name = "Circle";

    public Circle() {
        System.out.println("This is constructor of Circle!");
    }

    @Override
    public void getName() {
        System.out.println("This is getName of Circle! ");
    }

    public void getSuperName() {
        System.out.println(super.name);
    }

    public static void getSname() {
        System.out.println("Here is static getName of Circle");
    }

}

然后有一个测试类:

public class Test {

    public static void main(String[] args) {
        Shape shape = new Circle();
        System.out.println(shape.name);
        shape.getName();
        Shape.getSname();
        Circle.getSname();
        Circle circle = new Circle();
        circle.getSuperName();
        System.out.println(circle.name);
    }
}

读者可以先自己思考一下结果会是什么。

可以给大家看看结果:

Everything begins here!
Here is constructor of Shape!
This is constructor of Circle!
Shape
This is getName of Circle! 
Here is static getName of Shape
Here is static getName of Circle
Everything begins here!
Here is constructor of Shape!
This is constructor of Circle!
Shape
Circle

下面一步一步的解析结果

第一句语句Shape shape = new Circle();

得到的结果是:

Everything begins here!
Here is constructor of Shape!
This is constructor of Circle!

Shape是放在栈中的地址,只是带了个偏移量。

new Circle(); 会在堆中新建一个对象。新建一个对象的时候,会先新建父类的对象,如果父类的对象有父类就先新建父类的结构以此类推。

System.out.println(shape.name);得到的结果是Shape

这是因为在内存堆中新建的对象类似一个叠起来的塔。而声明Shape的栈地址会指到带了这个偏移量的Circle父类Shape。所以声明了Shape可以使用shape中的一切有的方法。
Java继承关系的理解_第1张图片

shape.getName();得到结果是子类的方法,结果是Shape。子类的方法可以覆盖父类的方法。如下:

Java继承关系的理解_第2张图片

静态区存了静态方法和静态变量,所以每个类都有自己的静态方法和静态类。访问的时候直接是访问静态区,所以静态方法的调用方式为:Shape.getSname();

所以结果是Here is static getName of Shape

而其它的调用结果原理同上,结果很容易得出。

你可能感兴趣的:(Java基础&源码解析)