0% found this document useful (0 votes)
10 views6 pages

Constructors in Java With Examples

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Constructors in Java With Examples

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

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.

You might also like