-2
        /*package whatever //do not write package name here */
        //package inheritance;

        import java.util.*;
        import java.lang.*;

        class Dog{

            public static String Name="Miku";

            public void bark(){
                System.out.println("The Dog is Barking");   //class methods
            }

            public void run(){
                System.out.println("The Dog is runing");    //class methods
            }
        }

I have not declared variable "Name" how is it able to overwrite super class variable. Plaese explain how is the variable "Name" working here

        class Hound extends Dog{            
                                                           //Overridden method bark()
            public void bark(){
                super.bark();
                Name="Doggo";

                System.out.println("The Hound " +this.Name +" is barking");
                System.out.println("The Hound " +super.Name +" is barking");
            }
        }

        public class Test6{
            public static void main(String Args[]){

                Hound H=new Hound();
                H.bark();
            }
        }

The output to the code is

           The Dog is Barking
           The Hound Doggo is barking
           The hound Doggo is barking

2 Answers2

0

it is not overridden. it is inherited by the child class Hound.

By the definition "Static methods and variables are inherited from super-class to subclass, as long as the the method is accessible to the subclass. By that I mean if the child-class(subclass) is in different package then, as long as the method is declared public or protected in the superclass it will be inherited in the subclass."

so your hound class has access to the variable name and it is not final so the value can be changed by the methods of the inheriting class hound.

  • ok but inside bark i have changed the "Name" to doggo. I have not declared the variable "Name" why isnt it throwing an error. please clarify. – Kaustuva Kumar Sahu May 04 '20 at 12:00
  • when the hound class extended Dog class, then it automatically has all the variables and methods that Dog offers and that is accessible as per the access privilage. so Hound not only has access to bark() and run() methods, but also to the "Name" variable. – Vijay Kumar May 06 '20 at 13:20
0

It is NOT overriding.
Since it is public and NOT final, you have access to modify it.
Since it is static, you are actually changing the parent value from the same memory space.

For more details, follow this link.

alexandrum
  • 429
  • 9
  • 17