2016-07-07 109 views
-2

我有一个情况超类/子类方法

public class Animal 
{ 
    String noise; 

    public String makeNoise() 
    { 
     return noise; 
    } 
} 

这时会出现与噪声的具体定义一个子类。

public class Dog extends Animal{ 
    String noise = "woof"; 
} 

public class Cat extends Animal{ 
    String noise = "meow"; 
} 

我想要做的就是

Animal cat = new Cat(); 
cat.makeNoise(); // This will be 'meow' 

Animal dog = new Dog(); 
dog.makeNoise(); // This will be 'woof' 

基本上,我不想重复makeNoise()方法当我创造一个动物。但是,这不起作用。 (噪声是空字符串)

我可以使用一个静态对象像

static String NoiseDog = "woof" 
static String NoiseCat = "meow" 

但再我必须写对每只动物的makeNoise()方法。有没有更好的方法来设计这个?

+2

设置在每个子类的构造函数的超类的噪音成员。你只需要在super中实现makeNoise()。 – bhspencer

回答

0

使Animal类的抽象。这样,就不会有如Animal对象那样的东西,它调用makeNoise

然后,将noise String设置为适合该动物声音的每个子类的构造函数中的值。

+0

同样的问题。我有大量的参数是每个子类特有的。 – user2689782

+0

如果它们是特定于子类的,则不必将它们作为参数传递给构造函数。只需在构造函数体中设置值即可。 – Zircon

+0

在超类的构造函数中设置值?还是子类? – user2689782

1
public class Cat extends Animal{ 
    String noise = "meow"; 
} 

这将创建一个名为“noise”的实例变量来隐藏超类变量。 相反,你需要用它来设置超值:

public class Cat extends Animal{ 
    public Cat() { 
     noise = "meow"; 
    } 
} 
+0

我不明白这一点? – user2689782

+0

@ user2689782这将超类中的字符串噪声设置为“喵”,给你你想要的结果。 – Orin

2

如果要强制Animal所有子类有noise定义,您可以实现在构造函数中:

public abstract class Animal { 
    private final String noise; 

    public Animal(final String noise) { 
     this.noise = noise; 
    } 

    public String makeNoise() { 
     return noise; 
    } 
} 

然后犬:

public class Dog extends Animal { 
    public Dog() { 
     super("woof"); 
    } 
} 

和猫:

public class Cat extends Animal { 
    public Cat() { 
     super("meow"); 
    } 
} 

并对其进行测试:

public class Test { 
    public static void main(String[] args) { 
     final Animal dog = new Dog(); 
     System.out.println(dog.makeNoise()); 
     final Animal cat = new Cat(); 
     System.out.println(cat.makeNoise()); 
    } 
} 

输出:

woof 
meow 
+0

谢谢你。在我的真实世界的例子中,有5个不同的参数需要为每个类别设置不同的参数。所以在构造函数中传递5个值并不容易。 – user2689782

+0

@ user2689782如果你有5个参数传递给'Animal',你可以将这些参数包装到另一个类'AnimalCharacteristics'中,并将其传递给'Animal'。 –

+0

嗯,很酷的想法。 – user2689782

0

或者,你可以实现一个接口:

动物:

public interface Animal { 
    public String makeNoise(); 
} 

犬:

public class Dog implements Animal { 
    public String makeNoise() { 
     return "woof"; 
    } 
} 

猫:

public class Cat implements Animal { 
    public String makeNoise() { 
     return "meow"; 
    } 
} 

测试:

public class Test { 
    public static void main(String[] args) { 
     Animal dog = new Dog(); 
     System.out.println(dog.makeNoise()); 
     Animal cat = new Cat(); 
     System.out.println(cat.makeNoise()); 
    } 
} 

输出:

woof 
meow 
+0

在这种情况下,我必须在每个类中定义makeNoise()方法。我试图摆脱这一点。 – user2689782