ADVERTISEMENT
ADVERTISEMENT

Java program to implement default or no-argument constructor

Learn how to implement default or no-argument constructor in Java?
Submitted by Nidhi, on March 21, 2022

Problem Solution:

In this program, we will create a Sample class and implement a default or no-argument constructor.

A constructor is a special type of method that initializes data members of the class and instantiates the object.

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 num1, num2, 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.

Java Class and Object Programs »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.