Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

General Form of a Class

Posted By: Leigh Carpenter     Category: Java     Views: 4305

This article explains about general form of class in java.

Class is the means by which you define objects. A class may contain three types of items : variables, methods and constructors. 

Variables represent its state. Class can have static and instance variables. Methods provide the logic that constitutes the behavior defined by a class. Class can have static and instance methods. Constructors initialize the state of a new instance of a class.

General form or Syntax of a Class

class clsName
{
// instance variable declaration
type1 varName1 = value1;
type2 varName2 = value2;
:
:
typeN varNameN = valueN;

//  Constructors 
clsName(cparam1)
{
// body of constructor
}
:
:
clsName(cparamN)
{
// body of constructor
}

// Methods
rType1 methodName1(mParams1)
{
// body of method
}
:
:
rTypeN methodNameN(mParamsN)
{
// body of method
}
}

class indicates that a class named clsName is being declared. It must follow the java naming conventions for identifiers.

Instance variables named varName1 through varNameN are normal variable declaration syntax. Each variable must be assigned a type shown as type1 through typeN and may be initialized to a value shown as valueN. 

Constructors always have the same name as the class. They do not have return values. cparam1 through cparamN are optional parameter lists.

Methods named mthName1 through mthNameN can be included. The return type of the methods are rtype1 through rTypeN and mParamN aew an optional parameter lists.


Example of a General Class

class clsSample
{
// Variables
static int ctr;
int i;
int j;

// Constructor
clsSample()
{
ctr = 0;
i = 0;
j = 0;
}
clsSample(int a, int b, int c)
{
ctr = a;
i = b;
j = c;
}

// Methods 
int addition()
{
ctr++;
return i + j;
}
int NumberOfInstances()
{
return ctr;
}
}


Creating Object of clsSample Class

clsSample smpObj = new clsSample();


  
Share: 

 
 

Didn't find what you were looking for? Find more on General Form of a Class Or get search suggestion and latest updates.

Leigh Carpenter
Leigh Carpenter author of General Form of a Class is from Chicago, United States.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!