相关疑难解决方法(0)

为什么java多态在我的例子中不起作用

我有这4个java clases:1

public class Rect {
    double width;
    double height;
    String color;

    public Rect( ) {
        width=0;
        height=0;
        color="transparent";      
    }

    public Rect( double w,double h) {
        width=w;
        height=h;
        color="transparent";
    }

    double area()
    {
        return  width*height;
    } 
}
Run Code Online (Sandbox Code Playgroud)

2

public class PRect extends Rect{
    double depth;

    public PRect(double w, double h ,double d) {
        width=w;
        height=h;
        depth=d;
    }

    double area()
    {
        return  width*height*depth;
    }     
}
Run Code Online (Sandbox Code Playgroud)

3

public class CRect extends Rect{ 
    String color;

    public CRect(double w, double h ,String c) { …
Run Code Online (Sandbox Code Playgroud)

java polymorphism subclass superclass

6
推荐指数
1
解决办法
1877
查看次数

静态实例变量查找Java

class A {int x = 5;}
class B extends A {int x = 10;}
class D {
    public static void main(String[] args){
        A b0 = new B();
        System.out.print(b0.x);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道为什么这个代码打印5而不是10.

如果我改为编写以下内容,将变量x转换为方法,它的工作方式就像我期望的那样,并打印出10,因为在编译时它只检查b0的静态类型A是否有方法x,然后是运行时,使用b0的动态类型B来运行x.

class A {int x() {return 5;}}
class B extends A {int x() {return 10;}}
class D {
    public static void main(String[] args){
        A b0 = new B();
        System.out.print(b0.x());
    }
}
Run Code Online (Sandbox Code Playgroud)

我的理论是,与方法不同,实例变量是静态查找的,但我不确定为什么会这样.

谢谢!

java static dynamic

5
推荐指数
1
解决办法
1140
查看次数

标签 统计

java ×2

dynamic ×1

polymorphism ×1

static ×1

subclass ×1

superclass ×1