2013-11-23 39 views
0

这里是我的问题: 我有一个Piece类,它有方法getName返回“P”(它只是一个例子) 我有另一个类King扩展Piece并且有重新定义了getName方法返回“K”。如何选择使用基于变量类型的方法

现在我有一个Piece(Piece []数组)的数组(在这个数组中有实例King的对象) 当我从所有这些对象中调用getName时,我总是从所有对象中获得“P”。 我想从King对象中获得“k”,从Piece对象中获得“P”。 下面是一个示例:

Piece[] p = new Piece[1]; 
p[0] = new King(); 
p[0].getName() //I got "P" not "K" 

如何解决我的问题?

谢谢。

+4

向我们展示代码。我们会帮助你更容易。 –

回答

2

既然你没有表现出任何的代码,我会告诉你一个简单的例子:

public class Piece { 

    public String getName() { 
     return "P"; 
    } 
} 

public class King extends Piece { 

    @Override 
    public String getName() { 
     return "K"; 
    } 
} 

public class JavaTest { 

    public static void showNames(Piece[] p) { 
     for (Piece x : p) { 
      System.out.println(x.getName()); 
     } 
    } 

    public static void main(String[] args) { 

     Piece[] p = new Piece[]{ 
      new Piece(), 
      new King() 
     }; 

     showNames(p); 
    } 
} 

输出

P 
K 
+0

谢谢我忘了@Override。现在我知道我们为什么要使用它 –

+0

@rabahRachid你从来没有声明过你是否将'Piece'变量存储在'Piece []'或者'King'中。我假设后者,因此我的答案是基于此。看到我的新答案。 =) –

+0

这是另一个问题,我会提出另一个问题 –

-2

以前的答案被删除

我已经纠正在我以前的答案错误拿出一个解决方案。我在名为getSpecificName()的子类中添加了一个新方法,它接受一个参数int来决定调用哪个getName(),从而为您提供适当的值。

的代码可以在这里找到:http://ideone.com/ioF06I

/* package whatever; // don't place package name! */ 

import java.util.*; 
import java.lang.*; 
import java.io.*; 

class IdeoneBase{ 

    public String getName(){ 
     return "P"; 
    } 
} 

/* Name of the class has to be "Main" only if the class is public. */ 
class Ideone extends IdeoneBase 
{ 
    @Override 
    public String getName(){ 
     return "K"; 
    } 

    String getSpecificName(int x){ 
     if(x == 1){ 
      return super.getName(); 
     } 
     return getName(); 
    } 

    public static void main (String[] args) throws java.lang.Exception 
    { 
     IdeoneBase piece = new Ideone(); 
     if(piece instanceof Ideone){ 
      Ideone p = (Ideone) piece; // without this downward cast, you cannot call getSpecificName(). You can only call that is common between the two. 
      System.out.println(p.getSpecificName(1)); 
      System.out.println(p.getSpecificName(999)); 
     } 
    } 
} 
+0

有没有解决方法? –

+0

是的,将“Piece”下降到“King”,然后调用该方法。我知道我的例子是愚蠢的,但为了方便起见,我使用了这个例子。使用像'piece [0] instanceof King {...}'这样的检查' –

+1

如果方法被覆盖,那么调用覆盖类的方法,而不是父类的方法。我只是测试了这一点。 – Makoto

2

你可能想要做的是使Piece一个抽象类。因为它是可能不会直接实例化一个基类,你将有其他类扩展它有哪些具体的类,即 - 国王,王后,典当,鲁克,主教,骑士等

public abstract class Piece { 

    ... // other code 

    public abstract String getName(); 

    ... // other code 
} 

public class King extends Piece { 

    ... // other code 

    @Override 
    public String getName() { 
     return "K"; 
    } 

    ... // other code 
} 
2

你绝对肯定,King extends Piece

这就是所谓的is-a的关系。 A KingPiece,因此它从Piece继承是有意义的。

public class Piece { 
    public String getValue() { 
     return "P"; 
    } 
} 

public class King extends Piece { 
    public String getValue() { 
     return "K"; 
    } 
} 

有了这个,当你实例化一个新KinggetValue()将返回"K",如您所愿。