Java – Calling Non Static Members Directly From Constructor Without Using the Object Name
Last Updated :
24 Sep, 2021
Java is an Object-Oriented Programming(OOP) language. We need to create objects in order to access methods and variables inside a class. However, this is not always true. While discussing static keywords in java, we learned that static members are class level and can be accessed directly without any instance. Here we will be discussing how we can access non-static data members without using the object name for which let us compare static data members and non-static data members which are as provided in the below table as follows:
Static Data Members |
Non-Static Data Members |
They are declared using the keyword ‘static’. |
Every member in java defaults to a non-static without a ‘static’ keyword preceding it. |
All objects of a class share the same copy of static data members. |
Each object of the class gets its own copy of Non-Static data members. |
They can be accessed using the class name or object. |
They are generally accessed through an object of the class. |
Static methods can be called without the instance or object of that class. |
Non-static methods can access any static method and static variable, without creating an instance of the object. |
Example 1: Calling static data members without the instance or object of that class.
Java
public class GFG {
static int a = 5 ;
static void f()
{
System.out.println( "I am static method" );
}
public static void main(String[] args)
{
System.out.println(GFG.a);
GFG.f();
}
}
|
Output
5
I am static method
Example 2: Calling non-static data members.
Java
public class GFG {
int a = 5 ;
void f()
{
System.out.println( "I am Non-static method" );
}
public static void main(String[] args)
{
GFG obj = new GFG();
System.out.println(obj.a);
obj.f();
}
}
|
Output
5
I am Non-static method
Example 3: Calling non-static data members directly without using object names.
Java
class GFG {
GFG()
{
int a = 5 ;
System.out.println(a);
display();
}
void display()
{
System.out.println(
"Non static method is called using constructor." );
}
public static void main(String[] a) { new GFG(); }
}
|
Output
5
Non static method is called using constructor.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...