Skip to content

Commit

Permalink
Dynamic Polymorphism
Browse files Browse the repository at this point in the history
  • Loading branch information
KatsuMouley committed May 13, 2024
1 parent 0bd15c0 commit a3badc6
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/App.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
public class App {
//Each Exercise can run individualy, but I intend to create a main code where all the exercises with explanations can be outputted.
public static void main(String[] args) {
System.out.println(" Lets run the codes! ");
System.out.println(" I'm still working on the codes. But for now, you can run each one individualy");
}
}
3 changes: 3 additions & 0 deletions src/Objects/Animal.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,7 @@ public class Animal {
public void speak(){
System.out.println("The animal is speaking");
}
public void animalSpeak(){
System.out.println("*grrr*");
};
}
12 changes: 12 additions & 0 deletions src/Objects/Cat.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package Objects;

public class Cat extends Animal {
@Override
public void speak(){
System.out.println("Cat goes MEOW MEOW MEOW MEOOOOOOOOOOOOOW");
}
@Override
public void animalSpeak(){
System.out.println("*meow*");
}
}
4 changes: 4 additions & 0 deletions src/Objects/Dog.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,8 @@ public class Dog extends Animal{
public void speak() {
System.out.println("The dog goes *bark*");
}
@Override
public void animalSpeak(){
System.out.println("*bark*");
}
}
36 changes: 36 additions & 0 deletions src/files/DynamicPolymorphism.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package files;

import java.util.Scanner;

import Objects.Animal;
import Objects.Cat;
import Objects.Dog;

public class DynamicPolymorphism {
public static void main(String[] args) {
run();
}
public static void run() {
Scanner scanner = new Scanner(System.in);
Animal animal;

System.out.println("What animal do you want?");
System.out.print("(1=dog) or (2=cat): ");
int choice = scanner.nextInt();

if(choice==1) {
animal = new Dog();
animal.speak();
}
else if(choice==2) {
animal = new Cat();
animal.speak();
}
else {
animal = new Animal();
System.out.println("That choice was invalid");
animal.speak();
}
scanner.close();
}
}

0 comments on commit a3badc6

Please sign in to comment.