Access Super Class Methods and Instance Variables Without super Keyword in Java
Last Updated :
25 Nov, 2022
A class describes the property and the attributes of the object. A class contains mainly includes the following components.
- Modifiers: The keywords in java which provide a set of restriction on the class and its members and methods.
- Class keyword: The initialization of the class is done by class reserved word and following by the name of the class.
- Class Name: The name of the class that must follow the rules as follows while creating the variables in java.
Super class : The parent class from which many subclasses can be created. All the subclasses have all the attributes and properties that have parent class.
Inheritance is the mechanism of object-oriented language by which any class can (child class) inherit other class all the properties and behaviour of the parent class.
Parent class: GFG
Child class: GFGChild
Simple Format of Inheritance:
Java
import java.io.*;
class GFG {
}
class GFGChild extends GFG {
}
|
There are two methods to call the instance variables and methods of the superclass (parent class) in the child class.
1. First Method: super keyword is one of the reserved words in java. Super refers to an object of the parent class. (Refer to this article).
Uses:
- We can invoke the overridden method of the parent class with the help of the super keyword.
- super() is used for executing the constructor of the parent class and should be used in the first line in the derived class constructor.
Implementation:
Java
import java.io.*;
class helloworld {
String name = "helloworld is the name" ;
void print()
{
System.out.println( "This is the helloworld class" );
}
}
class GFG1 extends helloworld {
String name = super .name;
void print()
{
super .print();
System.out.println( "This is the GFG1 class" );
System.out.println(name);
}
}
class GFG {
public static void main(String[] args)
{
GFG1 ob = new GFG1();
ob.print();
}
}
|
Output
This is the helloworld class
This is the GFG1 class
helloworld is the name
2. Second Method: Without using the keyword super keyword after inheritance all the methods and instance variables of the parent class is inherited by the child class. So we can direct them in the child class.
GFG class: parent class
Arraylist class: Derived class
Implementation:
Java
class Arraylist extends GFG {
void hello()
{
System.out.println( "This is the Main class" );
}
public static void main(String args[])
{
Arraylist ob = new Arraylist();
ob.name();
}
}
class GFG {
GFG()
{
System.out.println( "This is the constructor" );
}
void name() { System.out.println( "Hello world" ); }
}
|
Output
This is the constructor
Hello world
Share your thoughts in the comments
Please Login to comment...