JAVA
CONSTRUCTOR
What is a Constructor in Java?
•A constructor in Java is a special method that is used to initialize
objects.
It looks like a method but has no return type (not even void),
and its name must be same as the class name.
• Ex: write below code and save file as [Link]
class condemo{
}
#javac [Link]
#javac –p condemo
Key Points:
• Same name as class
• No return type (not even void).
• Called automatically when an object is created.
• Types of constructors:
• Default constructor – provided by Java if no constructor is written.
• No-argument constructor – you write it with no parameters.
• Parameterized constructor – takes arguments to initialize fields.
• Copy constructor (not built-in) – you can write one to copy
values from another object.
Access Modifier in Constructor
• Access Modifiers in Constructor
• In
Java, just like methods, a constructor can have access
modifiers (public, protected, default, private).
• 1. Public Constructor
• Can be accessed from anywhere.
• Most common case.
Default Constructor
•. Default (No Modifier) Constructor
• Accessible only within the same package.
• Youcan create objects inside the same package,
but not from outside the package.
Protected Constructor
• Accessible in the same package.
• Also accessible in subclasses (even in other packages).