Constructor:- Java में object के जरिये किसी भी variable को dot(.) Operator के माध्यम से अलग अलग access किया जा सकता है। या तो किसी method का use करके object को initialize किया जा सकता है।
Object के create होते ही उसे initialize करने के तरीके को एक special method के जरिए किया जाता है।
Object के create होते ही उसे initialize करने के तरीके को एक special method के जरिए किया जाता है।
Constructor का नाम वही होता है। जो कि class का नाम होता है।
Constructor का कोई return type नही होता है।
Program : ( application of constructors)
Class width
{
Int length , width ;
Rectangle( int x , int y)// defining constructor
{
Length= x ;
Width = y;
}
Int rectArea ()
{
Return ( length * width )
}
}
Class rect area
{
public static void main(String args [ ] )
{
Rectangle r1 = new rectangle ( 5, 10);//calling
Int area 1 = rect 1 . area ( );// constructor
System . out . printin ( ” area 1 = ” + area );
}
}
Output of program
Area 1 = 150