Monday, 6 February 2017

Accessing Instance Variables and Methods

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

import java.io.*;
public class Rahul
{
 
int rahulAge;



    public Rahul(String name)
{
      // This constructor has one parameter, name.
     
System.out.println("Name chosen is :" + name );
 
}

 
public void setAge( int age )
{
     
rahulAge = age;
 
}

 
public int getAge( )
{
     
System.out.println("Rahul's age is :" + rahulAge );
     
return rahulAge;
 
}

public static void main(String []args)
{
      /* Object creation */
     
Rahul myRahul = new Rahul( "Rahul" );

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

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

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

}



Result will be :
Name chosen is :Rahul
Rahul's age is :2
Variable Value :2

No comments:

Post a Comment