This is the source class for ‘myObject’. In line 3 we have declared a instance variable (known as a class field, because it declares inside class block, not in a method). ‘setText’ method will set a value to strText, and ‘getText’ method will return the value in strText.
Save this class as “InstanceVariables.java”
public class InstanceVariables
{
String strText;
public void setText()
{
strText = "This is VariableUserMethod";
}
public string getText()
{
return strText
}
}
This is the class which uses “InstanceVariables.java” through the object “myObject”.
public class TextEdit
{
public static void main(String[] args)
{
InstanceVariables myObject = new InstanceVariables();
//without arguments
InstanceVariables myArgObject = new InstanceVariables("With Arguments");
System.out.println("Getting the value with myObject");
System.out.println("Value is:" + myObject.getText());
System.out.println("Getting the value with myNewObject");
System.out.println("Value is:" + myArgObject.getText());
}
}
This is the output:
Tip: An object is constructed by instantiating a class. The process of creating an object of a class is called as instantiation and the created object is called as an instance.
No comments:
Post a Comment