Advertisement
thotfrnk

ex4-6.java

Jun 7th, 2023
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | None | 0 0
  1. public class Animal {
  2.     //private instance variable
  3.     private final String name;
  4.  
  5.     //constructors
  6.     public Animal(String name) {
  7.         this.name = name;
  8.     }
  9.  
  10.     public String toString() {
  11.         return "Animal: Animal[name = " + name + "]";
  12.     }
  13. }
  14.  
  15. //next class
  16.  
  17. public class Mammal extends Animal {
  18.     //constructors
  19.     public Mammal(String name) {
  20.         super(name);
  21.     }
  22.  
  23.     @Override
  24.     public String toString() {
  25.         return "Mammal: Mammal[ " + super.toString() + "]";
  26.     }
  27. }
  28.  
  29. //next class
  30.  
  31. public class Cat extends Mammal {
  32.     //constructors
  33.     public Cat(String name) {
  34.         super(name);
  35.     }
  36.  
  37.     public void Greets() {
  38.         System.out.println("Meow");
  39.     }
  40.  
  41.     @Override
  42.     public String toString() {
  43.         return "Cat: Cat[ " + super.toString() + "]";
  44.     }
  45. }
  46.  
  47. //next class
  48.  
  49. public class Dog extends Mammal {
  50.     //constructor
  51.  
  52.     public Dog(String name) {
  53.         super(name);
  54.     }
  55.  
  56.     public void Greets() {
  57.         System.out.println("Woof");
  58.     }
  59.  
  60.     public void Greets2(String name) {
  61.         System.out.println("Woooof");
  62.     }
  63.  
  64.     @Override
  65.     public String toString() {
  66.         return "Dog: Dog " + super.toString() + "]";
  67.     }
  68. }
  69.  
  70. //test class
  71.  
  72. public class testAnimal {
  73.     public static void main(String[] args) {
  74.         //to test animal class
  75.         Animal a1 = new Animal("Rino");
  76.  
  77.         System.out.println(a1);
  78.  
  79.         System.out.println();
  80.  
  81.         //to test mammal class
  82.         Mammal m1 = new Mammal("Dolphin");
  83.  
  84.         System.out.println(m1);
  85.  
  86.         System.out.println();
  87.  
  88.         //to test cat class
  89.         Cat c1 = new Cat("Nyancheng");
  90.  
  91.         System.out.println(c1);
  92.         c1.Greets();
  93.  
  94.         System.out.println();
  95.  
  96.         //to test dog class
  97.         Dog d1 = new Dog("Golden Retriever");
  98.         Dog d2 = new Dog("Husky");
  99.  
  100.         System.out.println(d1);
  101.         d1.Greets();
  102.         d2.Greets2("Husky");
  103.  
  104.     }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement