اتحاد طلبة هندسة الحاسوب والشبكات - المدونه الرسميه C.N.E : Object Oriented Programming Using Java-8

المشاركات الشائعة

Object Oriented Programming Using Java-8


Constructors
A constructor is a special method that has the same name of its class, it is called automatically when an object from the class is created, it is usually used to initialize the instance variables with values often passed by user through the constructor's parameter list.
That's why it is called a constructor, because it constructs the instance variables with values.

However, a constructor is not necessarily initializes the instance variables because its code is written by user, user can write any statements insider the constructor's body.



As mentioned above, the constructor must has the same name of its class. To see how a constructor is declared, consider the following general syntax:
access-modifier class-name (parameter-list)
{ constructor-body }

Where:

access-modifier: often public or private.
class-name: it is the name of the class which contains this constructor.
parameter-list: a comma separated arguments to pass values through the constructor body.
constructor-body: any programming statements.

As you can see from the general syntax, the constructor is the same as any other method except that it has no return type and its name must be the same as the class name.

As the normal methods, a constructor can be overloaded. Therefore, we have 2 types of constructors:
Default constructor
: It is referred to the constructor which has no parameter list.
Overloaded constructors
: It is referred to the constructors that have parameter list.

You can have only one default constructor for a class while unlimited number of overloaded constructors.

To understand how constructors work, consider the following example:


class program:



class Myprogram:



The output is:



As in overloaded methods, the compiler chooses the proper constructor according to the arguments passed through the object creation statement.

سامر المناصرة
< >

ليست هناك تعليقات:

إرسال تعليق