Chapter 08
Chapter 08
in Java
Chapter 08
Constructor
▪ Constructor is a special kind of method that is invoked when a new object is created.
▪ Constructor can perform any action; but it is mainly designed to perform initializing
actions.
▪ Every class is having its default constructor; sometimes referred to as no-argument
constructor.
▪ It initializes the attributes of a newly created object using default values based on
their data types.
▪ Constructor differs from general methods in the following ways:
– Constructor must have the same name as class name.
– Constructor does not have return type.
– Constructor is invoked implicitly only when an object is constructed using new operator.
– Constructor cannot be invoked explicitly elsewhere in the program.
– Like other methods, Constructor can also be overloaded.
Visibility Modifiers for Access
Control
▪ Access control is about controlling visibility. So, access modifiers are also
known as visibility modifiers.
▪ If a method or variable is visible to another class, then only it can be
referred in another class.
▪ To protect a method or variable from such references, we use the four
levels of visibility to provide necessary protection.
▪ The Four P's of protection are public, package (default protection),
protected and private.
▪ Access modifiers public, protected and private are used before the type
of variable or method.
▪ When no modifier is used, it is default one having visibility only within a
package that contains the class.
Visibility Modifiers for Access
Control
▪ Public
– Any method or variable is visible to the class in which it is defined.
– If we want to make it visible to all the classes outside this class, declare the
method or variable to have public access.
– This is the widest possible access.
– Example: public float length; public double area( );
Visibility Modifiers for Access
Control
▪ Package (Without any modifier)
– This is the next level of access that has no precise name.
– It is indicated by the lack of any access modifier keyword in a declaration.
– This the default level of protection.
– The scope is narrower than public variables.
– The variable or method can be accessed from anywhere in the package that contain the class but not from
outside that package.
– A source file without package statement is considered as package by default.
▪ Protected
– This level of protection is used to allow the access only to subclasses or to share with the methods declared as
“friend”.
– Thus the visibility is narrower than previous two levels; but wider than full privacy provided by fourth level
“private”.
▪ Private
– Highest level of protection can be achieved by using private protection level.
– This provides the narrowest visibility. The private methtods and variables are directly accessible only by the
methods defined with in a class.
– They cannot be seen by any other class.
Accessor and Mutator Methods