相关疑难解决方法(0)

Java中的变量阴影

我对这个Java代码有些怀疑.它给出的输出是"毛茸茸的bray".我的问题:

  1. 为什么我得到这个输出?
  2. 如何在ZooKeeper类中访问String对象引用"name"?
  3. 如果它与变量阴影有关,那么哪个变量被遮蔽?

码:

class Mammal {
   String name = "furry ";
   String makeNoise() { return "generic noise"; }
 }
 class Zebra extends Mammal {
   String name = "stripes ";
   String makeNoise() { return "bray"; }
 }
 public class ZooKeeper {
   public static void main(String[] args) { new ZooKeeper().go(); }
   void go() {
     Mammal m = new Zebra();
     System.out.println(m.name + m.makeNoise());
     //Output comes as "furry bray". Please explain this.
     //And how can we access the name variable, the one …
Run Code Online (Sandbox Code Playgroud)

java

39
推荐指数
3
解决办法
6154
查看次数

为什么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 ×2

polymorphism ×1

subclass ×1

superclass ×1