I am currently in the design mode for this problem:
Implement the Speaker interface that is predefined. Create three classes that implement Speaker in various ways. Create a driver class whose main method instantiates some of these objects and tests their abilities.
How would I go about designing this program and them moving into the coding stage. I want to use these three classes to implement the Speaker interface class: Politician, Lecturer, and Pastor class. The methods I want to use are:
public void speak(); public void announce (String str);
Now for my design and coding, how would I go about to declare and object reference variable and have that variable have multiple references?
It's simple really. In brief:
class ClassA implements Speaker
{
public void speak(){
System.out.println("I love Java") ; //implement the speak method
}
}
class ClassB implements Speaker //follow the example of ClassA
class ClassC implements Speaker //same as above
Speaker[] speakers = new Speakers{new ClassA(),new ClassB(),new ClassC()} ;
for(Speaker speaker: speakers)
speaker.speak(); //polymorphically call the speak() method defined in the contract.
See "What is an Interface?" http://docs.oracle.com/javase/tutorial/java/concepts/interface.html This will hopefully get you started with the basics you're looking for.
The start of the implementation would look something like the following...
class Politician implements Speaker
{
public void speak()
{
// Method implementation
}
public void announce (String str)
{
// Method implementation
}
}
class Lecturer implements Speaker
{
public void speak()
{
// Method implementation
}
public void announce (String str)
{
// Method implementation
}
}
class Lecturer implements Speaker
{
public void speak()
{
// Method implementation
}
public void announce (String str)
{
// Method implementation
}
}
public static void main(String [] args)
{
Speaker s1 = new Politician();
Speaker s2 = new Pastor();
Speaker s3 = new Lecturer();
// Do something...
}
Use a Factory Method Design Pattern.. Check this article at http://en.wikipedia.org/wiki/Factory_method_pattern
Your code could look something like this, if you use the Factory pattern
public class SpeakerFactory {
enum SpeakerEnum { POLITICIAN, LECTURER, PASTOR} ;
Speaker getSpeaker(SpeakerEnum speakerType) {
switch (speakerType) {
case POLITICIAN : return new Politician();
....
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.