0% found this document useful (0 votes)
9 views

Default Constructor Code

The document discusses Java default constructors and constructor overloading. It provides an example of a class with a default constructor that initializes fields to default values. It also provides an example class with multiple constructors, including one with no parameters and one that initializes fields using parameters.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Default Constructor Code

The document discusses Java default constructors and constructor overloading. It provides an example of a class with a default constructor that initializes fields to default values. It also provides an example class with multiple constructors, including one with no parameters and one that initializes fields using parameters.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Java default constructor work

public class MyClass {


private int x;
private String s;

// Constructor
public MyClass() {
// Default constructor provided by Java
}

// Method to print values


public void printValues() {
System.out.println("x = " + x);
System.out.println("s = " + s);
}

public static void main(String[] args) {


MyClass obj = new MyClass();
obj.printValues(); // Call the method to print values
}
}

Constructor Overloading

public class AddNumbers {


private int num1;
private int num2;
private int sum;

// Constructor with no parameters


public AddNumbers() {
num1 = 0;
num2 = 0;
}

// Constructor with two parameters


public AddNumbers(int a, int b) {
num1 = a;
num2 = b;
}

// Method to add numbers


public void add() {
sum = num1 + num2;
}

// Method to display the sum


public void displaySum() {
System.out.println("Sum: " + sum);
}

public static void main(String[] args) {


// Creating objects using different constructors
AddNumbers obj1 = new AddNumbers(); // Calls constructor with no parameters
AddNumbers obj2 = new AddNumbers(5, 7); // Calls constructor with two parameters

// Adding numbers for each object


obj1.add();
obj2.add();

// Displaying sums for each object


System.out.print("Object 1 - ");
obj1.displaySum();
System.out.print("Object 2 - ");
obj2.displaySum();
}
}

You might also like