0% found this document useful (0 votes)
2 views2 pages

Java Constructors Code Only

The document provides code examples of three types of Java constructors: Default, No-Argument, and Parameterized Constructors. Each example demonstrates how to create a class with a constructor and a display method to show the object's attributes. The Default constructor is auto-inserted by the compiler, while the No-Argument and Parameterized constructors allow for initializing object properties explicitly.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Java Constructors Code Only

The document provides code examples of three types of Java constructors: Default, No-Argument, and Parameterized Constructors. Each example demonstrates how to create a class with a constructor and a display method to show the object's attributes. The Default constructor is auto-inserted by the compiler, while the No-Argument and Parameterized constructors allow for initializing object properties explicitly.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Constructors – Code Examples

Default, No-Argument & Parameterized Constructors

1. Default Constructor
public class DefaultDemo {
String name;
int age;

// No constructor written here.


// Compiler auto-inserts:
// DefaultDemo() { }

void display() {
[Link]("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


DefaultDemo obj = new DefaultDemo();
[Link]();
}
}

2. No-Argument Constructor
public class NoArgDemo {
String name;
int age;

NoArgDemo() {
name = "Unknown";
age = 0;
}

void display() {
[Link]("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


NoArgDemo obj = new NoArgDemo();
[Link]();
}
}

3. Parameterized Constructor
public class ParamDemo {
String name;
int age;

ParamDemo(String n, int a) {
name = n;
age = a;
}

void display() {
[Link]("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


ParamDemo obj = new ParamDemo("Bharath", 19);
[Link]();
}
}

You might also like