'Does my code follows the principle of Polymorphism?
I'm a newbie to Java and I attempt to achieve Polymorphism with the requirements of using the following:
- super keyword
- overriding
- having more than two classes
- getting the user's input
- using do-while
- creating objects
It doesn't have any errors but I doubt if it still makes any sense. Does it follow Polymorphism still? If not, How can I improve it?
Here is my code:
public class Sample Code {
public static void main(String[] args) {
//declare variables
String name, fSong;
int aNum;
fSong = " ";
Zayn a1 = new Zayn();
a1.makeMusic();
Songs a2 = new Songs();
a2.setName("Zayn");
a2.displayName();
a2.makeMusic();
Lyrics a3 = new Lyrics();
a2.displayName();
a3.makeMusic();
//get values
Scanner in = new Scanner (System.in);
do{
System.out.print("Enter Your Name (2-20 characters): ");
name = in.nextLine();
}while(name.length() < 2 || name.length() > 20);
System.out.print("\nCHOOSE YOUR FAVORITE SONG :\n\n");
System.out.print("[1] Pillowtalk \n");
System.out.print("[2] Dusk Till Dawn\n");
do{
System.out.print("\nEnter Your Choice (1-2): ");
aNum = in.nextInt();
}while(aNum < 1 || aNum > 2);
//determine aNum
if(aNum == 1) {
fSong = "Pillowtalk";
}else if(aNum == 2){
fSong = "Dusk Till Dawn";
}
//Display output
System.out.print("\n[OUTPUT]\n\n");
System.out.printf("Your Name: %s\n", name);
System.out.printf("Your Favorite song of Zayn is: %s.\n", fSong);
}
}
class Zayn{
String name;
Zayn(){
this.name = this.name;
}
void makeMusic(){
System.out.println("Zayn makes music");
}
}
//superclass
class Songs extends Zayn{
Songs(){
super();
}
void makeMusic(){
System.out.println("Pillowtalk Lyrics: Pillowtalk, my enemy, my ally\n");
}
public void setName (String newName){
this.name = newName;
}
void displayName(){
System.out.println("\nName of Artist: " + this.name);
}
}
class Lyrics extends Zayn{
@Override
void makeMusic(){
System.out.println("Dusk Till Down Lyrics: I'll be with you from dusk till dawn\n");
}
}
Solution 1:[1]
So I don't think that will compile: public class Sample Code { as an example.
Does it follow Polymorphism
It sorta demonstrates it, but it doesn't look like a clear application of the principle.
What's a Zayn, and why is a Song a Zayn and a Lyric is a Zayn?
Polymorphism is to represent a hierarchical typing of your objects. E.g. you could have Animal as base class, with Mammal and Reptile extending. This can be further extrapolated to have Dog and Cat extend from Mammal, while Lizard and Snake extend from Reptile.
Bear in mind that if class Foo extends class Bar then any instance of Foo is also a Bar. This is sometimes called a "is-a" relationship, because in this scenario, a Foo is a Bar.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
