Constructors in Java
With Simple Examples and Output
What is a Constructor?
• • A constructor is a special method used to
initialize objects.
• • Same name as the class.
• • No return type.
• • Called automatically when an object is
created.
Default Constructor Example
• class Car {
• String brand;
• Car() {
• brand = "Tesla";
• }
• public static void main(String[] args) {
• Car c = new Car();
• [Link]([Link]);
• }
Parameterized Constructor
Example
• class Student {
• String name;
• int age;
• Student(String n, int a) {
• name = n;
• age = a;
• }
• public static void main(String[] args) {
• Student s = new Student("Alex", 20);
Copy Constructor Example
• class Book {
• String title;
• Book(String t) {
• title = t;
• }
• Book(Book b) {
• title = [Link];
• }
• public static void main(String[] args) {
Key Points about Constructors
• • Name must match class name.
• • Automatically called when object is created.
• • Cannot be abstract, static, or final.
• • Constructor overloading is allowed.