如何根据变量类型选择使用方法

时间:2013-11-23 19:06:03

标签: java parent-child

这是我的问题: 我有一个类Piece,其方法getName返回" P" (这只是一个例子) 我有另一个类King,它扩展了Piece并重新定义了getName方法以返回" K"。

现在我有一个Piece(Piece []数组)数组(在这个数组中有实例King的对象) 当我从所有这些对象中调用getName时,我总是得到" P"来自所有对象。 我想得到" k"来自King对象和" P"来自Piece对象。 这是一个例子:

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

如何解决我的问题?

感谢。

4 个答案:

答案 0 :(得分:2)

您可能想要做的是使Piece成为一个抽象类。由于它是一个可能不会直接实例化的基类,你将有其他类扩展它的具体类,即 - King,Queen,Pawn,Rook,Bishop,Knight等。

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
}

答案 1 :(得分: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

答案 2 :(得分:2)

您是否完全确定 King extends Piece

这称为是-a 关系。 KingPiece,因此从Piece继承是有道理的。

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

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

有了这个,当您实例化新的King时,getValue()会返回"K",正如您所期望的那样。

答案 3 :(得分:-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));
        }
    }
}