A simple Java class declaration with constructor declaration:
class simple
{
// Constructor
simple()
{
p = 1;
q = 2;
r = 3;
}
int p,q,r;
}
In class declaration, you can declare methods of the class:
class simple
{
// Constructor
simple()
{
p = 1;
q = 2;
r = 3;
}
int p,q,r;
public int addNumbers(int var1, int var2, int var3)
{
return var1 + var2 + var3;
}
public void displayMessage()
{
System.out.println("Display Message"); }
}
To invoke the class, you can create the new instance of the class:
// To create a new instance class
Simple sim = new Simple();
// To access the methods of the class
sim.addNumbers(5,1,2)
// To show the result of the addNumbers
System.out.println("The result is " + Integer.toString(addNumbers(5,1,2)));
The complete listing of class declaration:
class simple
{
// Constructor
simple()
{
p = 1;
q = 2;
r = 3;
}
int p,q,r;
public int addNumbers(int var1, int var2, int var3)
{
return var1 + var2 + var3;
}
public void displayMessage()
{
System.out.println("Display Message");
}
}
class example1
{
public static void main(String args[])
{
// To create a new instance class
Simple sim = new Simple(); // To show the result of the addNumbers
System.out.println("The result is " + Integer.toString(addNumbers(5,1,2))); // To display message
sim.displayMessage();
}
}
0 comments:
Post a Comment