Answer:
This JAVA program shows the implementation of instance variable and methods.
import java.util.Scanner;
import java.lang.*;
public class Person {
Scanner sc = new Scanner(System.in);
// instance variable declared without static keyword and outside of all methods
int age;
void getAge()
{
System.out.println("Enter your age");
age = sc.nextInt();
}
void display()
{
System.out.println("Entered age is " + age);
}
public static void main(String args[]) {
Person ob = new Person();
ob.getAge();
ob.display();
}
}
OUTPUT
Enter your age
45
Entered age is 45
Explanation:
A class contains its own variables and methods. An instance variable is declared inside the class and outside of all the methods contained in that class.
As specified in the question, the class Person contains one instance variable age and two methods, along with main() method.
Along with the instance variable age, an object of the Scanner class is created to enable input from the user. Both these variables are outside the methods. To enable user input, the required java package has been imported.
The two methods are defined to receive age and display age as mentioned in the question.
The input age is stored in the instance variable age.
void getAge()
{
System.out.println("Enter your age");
age = sc.nextInt();
}
This variable is used in display() to print the age.
void display()
{
System.out.println("Entered age is " + age);
}
All the methods are contained in a single class. Despite this, other methods can only be called through the object of the class which shows that JAVA is purely object oriented language.
public static void main(String args[]) {
Person ob = new Person();
ob.getAge();
ob.display();
}
As seen, the instance variable can be used by all methods contained in that particular class. The object of the class is only needed to call the method and not needed to use the instance variables.