Sample Program:
Case: This is an implementation of previous program. From line 5 to line 8 is the new part to study. That is the constructor. The constructor will execute automatically and assign a value to strText whenever method starts. Constructors do not have ‘void’ keyword.
public class InstanceVariables
{
String strText;
public InstanceVariables()
{
strText = "This value given by constructor";
}
public InstanceVariables(String text)
{
//opening constructor with an argument
strText = text;
}
//closing constructor with an argument
public void setText()
{
strText = "This is variableUser method.";
}
public String getText()
{
return strText;
}
}
This is the output:
No comments:
Post a Comment