fork download
  1. // Parent class
  2. class Animal {
  3. String name;
  4. 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.  
  20. // Child class inheriting from Animal
  21. class Dog extends Animal {
  22. String breed;
  23.  
  24. public Dog(String name, int age, String breed) {
  25. super(name, age); // Invoke superclass constructor
  26. this.breed = breed;
  27. }
  28.  
  29. public void bark() {
  30. System.out.println(name + " is barking.");
  31. }
  32. }
  33.  
  34. // Another child class inheriting from Animal
  35. class Cat extends Animal {
  36. String color;
  37.  
  38. public Cat(String name, int age, String color) {
  39. super(name, age); // Invoke superclass constructor
  40. this.color = color;
  41. }
  42.  
  43. public void meow() {
  44. System.out.println(name + " is meowing.");
  45. }
  46. }
  47.  
  48. public class Main {
  49. public static void main(String[] args) {
  50. // Creating instances of Dog and Cat
  51. Dog dog = new Dog("Buddy", 3, "Labrador");
  52. Cat cat = new Cat("Whiskers", 2, "White");
  53.  
  54. // Calling methods from parent class
  55. dog.eat(); // Inherited method
  56. cat.sleep(); // Inherited method
  57.  
  58. // Calling methods specific to child class
  59. dog.bark();
  60. cat.meow();
  61.  
  62. // Accessing fields
  63. System.out.println("Dog's breed: " + dog.breed);
  64. System.out.println("Cat's color: " + cat.color);
  65. }
  66. }
  67.  
Success #stdin #stdout 0.15s 55452KB
stdin
Standard input is empty
stdout
Buddy is eating.
Whiskers is sleeping.
Buddy is barking.
Whiskers is meowing.
Dog's breed: Labrador
Cat's color: White