JAVATECH NEWS

Java

CORE JAVA

Interview

OFF-CAMPUS

Saturday 8 November 2014

Preference of Super and Sub class:


In inheritance we always prefer to create the object of child class not the parent class,if we create the object of parent class it will access only the parent class member,to access both class member we should create the child class object.
If the Parent class and child class has the same member name(eg: instance variable and method) then by default it will call only child class member.

class Father       //Parent class
{
int age=60;               //Parent class instance variable
            void old()         //Parent class method
            {
            System.out.print("Age is : "+age);
            }
}

class Child extends Father       //Child class
{
int age=26;           //Child class instance variable
            void old()        //Child class method
            {
            System.out.print("Age is : "+age);
            }
}

class Preference
            {
            public static void main(String args[])
            {
                        Child ch=new Child();     //Child class object
                        ch.old();
            }
            }
O/P: Age is : 26
Now how to access the Super class or parent class member, for that we use “super” keword.We use super.variable for accessing super class variable and super.method() for super class method.Here is an example:


class Father       //Parent class
{
int age=60;               //Parent class instance variable
            void old()         //Parent class method
            {
            System.out.println("Age is Father : "+age);
            }
}

class Child extends Father       //Child class
{
int age=26;           //Child class instance variable
            void old()        //Child class method
            {
            System.out.println("Age of Child is : "+age);
           
            super.old();
           
            System.out.println("Age of Father is : "+super.age);
            }
}

class Preference
            {
            public static void main(String args[])
            {
                        Child ch=new Child();     //Child class object
                        ch.old();
            }

            }
O/P:Age of Child is : 26
      Age of Father is : 60
      Age of Father is : 60

No comments:

Post a Comment

Designed By Blogger Templates