Create a Java program to demonstrate method overriding with a subclass that overrides a method and broadens the access modifier from protected to public
Class hierarchy with a base class Animal and a subclass Dog. The makeSound method is declared in the Animal class and overridden in the Dog class. Here's an explanation of the code:
However, in your Dog class, you changed the access modifier of the makeSound method to public. This is allowed in Java, but it's important to note that it makes the method in the subclass more accessible than the method in the superclass.
When you run the code, it will create a Dog object and call the makeSound method. Since the makeSound method is overridden in the Dog class with the public access modifier, it will print "Dog barks" to the console.
class Animal { protected void makeSound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override public void makeSound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.makeSound(); } }
Dog barks
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions