class Rectangle
int length; //instance members
int breadth;
Every object has its seperate(own) copy of instance members.
class Demo
public static void main(String [] args)
{
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
[Link] = 4;
[Link] = 7;
S.o.p([Link]); //4
S.o.p([Link]); //7
}
--------------------------------------------------------
class Rectangle
{
static int length; //class member
class Demo
public static void main(String [] args)
{
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
[Link] = 4;
[Link] = 7;
S.o.p([Link]); //7
S.o.p([Link]); //7
}
---------------------------------------------------------
Constructors
class Rectangle
int length; //instance members
int breadth;
Rectangle( )
{
[Link]("My Constructor \n");
length = 5;
}
class Demo
public static void main(String [] args)
{
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
new Rectangle();
S.o.p([Link]); //5
S.o.p([Link]); //5
}
---------------------------
class Rectangle
{
int length; //instance members
int breadth;
Rectangle(int l ,int b)
{
[Link]("My Constructor \n");
length = l;
breadth = b;
}
public class ConstructorDemo {
public static void main(String [] args)
Rectangle r1 = new Rectangle(5 , 8);
Rectangle r2 = new Rectangle(6 , 3);
Rectangle r3 = new Rectangle();
[Link]([Link] +" " + [Link]);
[Link]([Link] +" " + [Link]);
}
If user provides parameterised constructor; then compiler does not provide the default
constructor.
---------------------------------
Constructors can be overloaded
class Rectangle
int length; //instance members
int breadth;
Rectangle()
{
[Link]("Default Constructor ");
}
Rectangle(int l ,int b)
{
[Link]("My Parameterised Constructor \n");
length = l;
breadth = b;
}
public class FunctionDemo {
public static void main(String [] args)
Rectangle r1 = new Rectangle(5 , 8);
Rectangle r2 = new Rectangle(6 , 3);
Rectangle r3 = new Rectangle();
[Link]([Link] +" " + [Link]);
[Link]([Link] +" " + [Link]);
}
-------------------------
class Rectangle
int length; //instance members
int breadth;
static int m_s;
{
[Link]("Instance Initialiser Block");
length = 1;
breadth = 1;
}
static
{
[Link]("Static Initialiser Block");
m_s = 4;
}
Rectangle()
{
[Link]("Default Constructor ");
}
Rectangle(int length ,int b)
{
[Link]("My Parameterised Constructor \n");
[Link] = length;
breadth = b;
}
static void statfunc()
{
//length = 5; //does not work
m_s = 1;
[Link]("Static Function");
}
void nonstatfunc()
{
m_s = 2;
length = 5; //works
[Link]("Non - Static Function");
}