Access instance members without any reference variable in java

Hi friends,

As we know we need reference variable to access instance members. Today we are going to learn that how we can access instance members without any reference variable.

Note : we can access only one instance member without reference variable and only once.

Please check following code…

class Student{
int roll;
String name;
void show(){
System.out.println(“This is show method”);
}
}class MyDemoClass{
public static void main(String[] args) {// Accessing class members with reference variable

// Student s1 = new Student();
// s1.show();

//—————————————

// Accessing class members with reference variable

new Student().show();

}
}

Output is

This is show method

Note:

Here, if we need to access one more instance member of Student class (roll, name)

OR

show() method one more time, then we may write this

new Student().show();

new Student.roll=10;

But, it will create one more instance…

So, remember again

Note : we can access only one instance member without reference variable and only once.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s