Advertisement
darrenbarnett

Untitled

Jun 17th, 2025
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. // Superclass
  2. public class Animal {
  3.     protected String name;
  4.     protected int age;
  5.    
  6.     public Animal(String name, int age) {
  7.         this.name = name;
  8.         this.age = age;
  9.     }
  10.    
  11.     public void eat() {
  12.         System.out.println(name + " is eating.");
  13.     }
  14.    
  15.     public void sleep() {
  16.         System.out.println(name + " is sleeping.");
  17.     }
  18.    
  19.     public String getName() {
  20.         return name;
  21.     }
  22.    
  23.     public int getAge() {
  24.         return age;
  25.     }
  26. }
  27.  
  28. // Subclass
  29. public class Dog extends Animal {
  30.     private String breed;
  31.    
  32.     public Dog(String name, int age, String breed) {
  33.         super(name, age);  // Call superclass constructor
  34.         this.breed = breed;
  35.     }
  36.    
  37.     public void bark() {
  38.         System.out.println(name + " is barking!");
  39.     }
  40.    
  41.     public String getBreed() {
  42.         return breed;
  43.     }
  44. }
  45.  
  46. public class Main {
  47.     public static void main(String[] args) {
  48.         Dog myDog = new Dog("Buddy", 3, "Golden Retriever");
  49.         myDog.eat();    // Inherited from Animal
  50.         myDog.sleep();  // Inherited from Animal
  51.         myDog.bark();   // Specific to Dog
  52.     }
  53. }
  54.  
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement