Q:

Java program to implement default or no-argument constructor

belongs to collection: Java Class and Object Programs

0

Java program to implement default or no-argument constructor

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to implement default or no-argument constructor is given below. The given program is compiled and executed successfully.

// Java program to implement default 
// or no-argument constructor

class Sample {
  int num1;
  int num2;

  Sample() {
    num1 = 10;
    num2 = 20;
  }

  void printValues() {
    System.out.println("Num1: " + num1);
    System.out.println("Num2: " + num2);
  }
}

class Main {
  public static void main(String args[]) {
    Sample obj = new Sample();
    obj.printValues();
  }
}

Output:

Num1: 10
Num2: 20

Explanation:

In the above program, we created a Sample class and public class Main. The Sample class contains data members num1num2, and a default constructor, a method printValues(). Here, we initialized data members using the default constructor.

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created object obj and called the printValues() method to print values of data members.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to implement constructor overloading... >>
<< Java program to create an array of objects...