Monday, November 15, 2021

Super Keyword in Java

The super keyword in java is a reference variable that is used to refer parent class objects. The super keyword refers to superclass (parent) objects.

The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

Usage of Java super Keyword:

  1. super can be used to refer immediate parent class instance variable.

Example:

class Vehicle

{

            int maxSpeed = 120;

}

class Car extends Vehicle

{

            int maxSpeed = 180;

            void display()

           {

            System.out.println("Maximum Speed: " + super.maxSpeed); //maxspeed of base

            }

}

class Test

{

            public static void main(String[] args)

            {

                        Car small = new Car();

                        small.display();

            }

}


  1. super can be used to invoke immediate parent class method.

Example:

class Person

{

            void message()

            {

                        System.out.println("This is person class");

            }

}

class Student extends Person

{

            void message()

            {

                        System.out.println("This is student class");

            }

            void display()

            {

                        message();

                        super.message();

            }

class Test

{

            public static void main(String args[])

            {

                        Student s = new Student();

                        // calling display() of Student

                        s.display();

            }

}


  1. super() can be used to invoke immediate parent class constructor.

Example:

class Person

{

            Person()

            {

                        System.out.println("Person class Constructor");

            }

}

class Student extends Person

{

            Student()

            {

                       super();

                        System.out.println("Student class Constructor");

            }

}

class Test

{

            public static void main(String[] args)

            {

                        Student s = new Student();

            }

}

0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top