Classes ,Objects and
methods
Class that defines the state and behaviour of
the basic program components known as
objects
Classes create objects and objects use
methods to communicate between them.
Data items are called as fields and the
functions are called methods.
continue
Class classname [extends superclassname]
{
[ variable declaration;]
[methods declaration;]
}
Class Empty
{
}
Adding Variables
Class Rectangle
{
int length;
int width;
}
these variables are only declared and
therefore no storage space is allocated to it.
Instance variables are called also called
member variables.
Method declaration
Method name
The type of the value the method return
Parameter list
The body of the method
class Rectangle
{
int length, width;
void getData(int x,int y)
{
length = x;
Width = y;
}
}
class Rectangle
{
int length, width; // combined declaration
void getData (int x,int y)
{
length = x;
Width = y;
}
Int rectArea()
{
Int area = length*width;
return(area);
}
}
}
Class Access
{ int x;
void method1()
{
int y;
x =10; //legal
y=x;
}
void method2()
{
int z;
x =5; //legal
z=10;
y=1; //illegal
}
}
Creating objects
Rectangle rect1; //declare
Rect1=new Rectangle() //instatiate
Rectangle rect1= new Rectangle() ;
Rectangle rect2= new Rectangle() ;
constructor
class Rectangle
{
int length, width; // combined declaration
void Rectangle (int x,int y)
{
length = x;
Width = y;
}
Int rectArea()
{
Int area = length*width;
return(area);
}
}