A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Accessing Instance Variables and Methods:

How are we accessing instance variables and methods in Java

How are we accessing instance variables and methods in Java?

Instance variables and methods are accessed via created objects. To access an instance variable the fully qualified path should be as follows:

* First create an object */ 
ObjectReference = new Constructor();

/* Now call a variable as follows */

/* Now you can call a class method as follows */

This example explains how to access instance variables and methods of a class: 

Example of accessing instance variables and methods in Java:-

public class Puppy 
 int puppyAge;

 /*This constructor has one parameter, name;*/
 public Puppy(String name)
  System.out.println("Passed Name is :" + name );
 public void setAge( int age )
  puppyAge = age;
 public int getAge( )
  System.out.println("Puppy's age is :" + puppyAge ); 
  return puppyAge;
 public static void main(String []args)
  /* Object creation */ 
  Puppy myPuppy = new Puppy( "tommy" );

  /* Call class method to set puppy's age */
  myPuppy.setAge( 2 );

  /* Call another class method to get puppy's age */
  myPuppy.getAge( );

  /* You can access instance variable as follows as well */
  System.out.println("Variable Value :" + myPuppy.puppyAge );


If we compile and run the above program then it would produce following result:  Passed Name is :Tommy
Puppy's age is :2 Variable Value :2