Overloading Constructors and Methods
This program demonstrates both constructor and method overloading.
Problem Statement
Write a Java program to overload constructors and methods in Book class.
Source Code
| 1 | class Book { |
| 2 | String title; int pages; |
| 3 | Book(){ title="Unknown"; pages=0; } |
| 4 | Book(String t,int p){ title=t; pages=p; } |
| 5 | void show(){ System.out.println("Title: "+title+", Pages: "+pages); } |
| 6 | void show(String prefix){ System.out.println(prefix+" Title: "+title+", Pages: "+pages); } |
| 7 | } |
| 8 | public class OverloadingConstructorsMethods { |
| 9 | public static void main(String[] args) { |
| 10 | System.out.println("Eduinq Overloading Constructors and Methods"); |
| 11 | Book b1=new Book(); |
| 12 | Book b2=new Book("Java Basics",200); |
| 13 | b1.show(); b2.show("Info:"); |
| 14 | } |
| 15 | } |
Program Output
Eduinq Overloading Constructors and Methods Title: Unknown, Pages: 0 Info: Title: Java Basics, Pages: 200
Explanation
Constructor overloading allows different ways to initialize objects. - Method overloading provides multiple versions of show() with different parameters. - This demonstrates flexibility in object creation and method usage, making classes more versatile and user friendly. Conclusion: Shows how to overload both constructors and methods.