Java Program to Illustrate Use of Constructor

«
»
This is a Java Program to Illustrate Use of Constructor.

Here we have made two types of constructor. One is simple and other is parametric. Now depending upon the object created, constructor gets started and hence we get the output.

Here is the source code of the Java Program to Illustrate Use of Constructor. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

advertisement
  1. public class Constructor
  2. {
  3.     double width;
  4.     double height;
  5.     double depth;
  6.     Constructor() 
  7.     {
  8. 	System.out.println("Constructor without parameter");
  9. 	width = 10;
  10. 	height = 10;
  11. 	depth = 10;
  12.     }
  13.     Constructor(int a, int b, int c) 
  14.     {
  15. 	System.out.println("Constructor with parameter");
  16. 	width = a;
  17. 	height = b;
  18. 	depth = c;
  19.     }
  20.     double volume() 
  21.     {
  22. 	return width * height * depth;
  23.     }
  24. }
  25. class ConstructorDemo
  26. {
  27.     public static void main(String args[]) 
  28.     {
  29. 	Constructor cuboid1 = new Constructor();
  30.         double vol;
  31. 	vol = cuboid1.volume();
  32. 	System.out.println("Volume is " + vol);
  33. 	Constructor cuboid2 = new Constructor(8,11,9);
  34. 	vol = cuboid2.volume();
  35. 	System.out.println("Volume is " + vol);
  36.     }
  37. }

Output:

$ javac ConstructorDemo.java
$ java ConstructorDemo
 
Constructor without parameter
Volume is 1000.0
Constructor with parameter
Volume is 792.0

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn