Constructor Overloading in Java with examples Like methods, constructors can also be overloaded. In this guide we will see Constructor overloading with the help of examples. Before we proceed further let’s understand what is constructor overloading and why we do it. Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.
class StudentData { private int stuID ; private String stuName ; private int stuAge ; StudentData () { //Default constructor stuID = 100; stuName = "New Student"; stuAge = 18; } StudentData ( int num1, String str , int num2) { //Parameterized constructor stuID = num1; stuName = str ; stuAge = num2; }
public int getStuID () { return stuID ; } public void setStuID ( int stuID ) { this.stuID = stuID ; } public String getStuName () { return stuName ; } public void setStuName (String stuName ) { this.stuName = stuName ; } public int getStuAge () { return stuAge ; } public void setStuAge ( int stuAge ) { this.stuAge = stuAge ; }
public static void main(String args []) { //This object creation would call the default constructor StudentData myobj = new StudentData (); System.out.println ("Student Name is: "+ myobj.getStuName ()); System.out.println ("Student Age is: "+ myobj.getStuAge ()); System.out.println ("Student ID is: "+ myobj.getStuID ()); /*This object creation would call the parameterized * constructor StudentData ( int , String, int )*/ StudentData myobj2 = new StudentData (555, " Chaitanya ", 25); System.out.println ("Student Name is: "+myobj2.getStuName()); System.out.println ("Student Age is: "+myobj2.getStuAge()); System.out.println ("Student ID is: "+myobj2.getStuID()); } }
Student Name is: New Student Student Age is: 18 Student ID is: 100 Student Name is: Chaitanya Student Age is: 25 Student ID is: 555
class Date { private int day; private int month; private int year; Date( int dd , int mm,int yy ) { System.out.println ("Constructor of Data Class is Called"); day= dd ; month=mm; year= yy ; } public String toString () { return (day+"/"+month+"/"+year); } }
class Employee { private int id; private String name; private Date hireDate ; //object of Data class Employee( int num,String n, Date hire) { System.out.println ("Constructor of Employee Class is Called"); id=num ; name=n ; hireDate =hire; } public void display() { System.out.println ("id = "+id); System.out.println ("Name = "+name); System.out.println (" Hiredate = "+ hireDate ); } }
public class Composition { public static void main(String[] args ) { Date d = new Date(01,01,2011); Employee emp = new mployee (1,"Dinesh Thakur",d ); emp.display (); } }
UserStatus.java public enum UserStatus { PENDING, ACTIVE, INACTIVE, DELETED; } CopyTest.java public class Test { public static void main(String[] args ) { //ACTIVE System.out.println ( UserStatus.ACTIVE ); } }
class EnumExample1{ public enum Season { WINTER, SPRING, SUMMER, FALL } public static void main(String[] args ) { for (Season s : Season.values ()) System.out.println (s); }}
Output: WINTER SPRING SUMMER FALL
public class Test { enum Color { RED, GREEN, BLUE; } // Driver method public static void main(String[] args ) { Color c1 = Color.RED ; System.out.println (c1); } } Output : RED
53 Java packages are classified into: Java API packages User Defined packages Java API Packages
54
56 Naming Conventions Packages cab be named using the standard java naming rules. However, package name begins with lowercase letters. double q = Java.lang.Math.sqrt(a); Package-name class-name method-name Here, statement uses a fully qualified class-name Math to invoke the method sqrt(). Every package name should be unique. Duplicate names will cause run-time errors.
57 Since multiple users work on internet, duplicate names are unavoidable. Java designers understands this problem and suggested package naming convention that ensures uniqueness. Example: cbe.psg.myPackage How to access package from another package? There are three way to access package from outside the package: import package.*; import package.classname ; Fully qualified name.
58 Creating Packages We must first declare name of the package using package keyword followed by package-name. This must be first statement in java program (source file).
59
60 Accessing a Package We must first declare name of the package using package keyword followed by package-name. This must be first statement in java program (source file).
61 using a Package Shows a package named package1 containing a single class ClassA. This source file should be named as CLassA.java and stored in subdirectory package1. now compile source file. It produces ClassA.class file and stored in the same subsidirectory.
62
63
64 Output :
65 When we import multiple packages it is likely that two or more packages contain classes with identical names. We may import and use these packages like:
66 Since both the packages contain the class Student , compiler cannot understand which one to use and therefore generates an error. In such instance, we have to be more explicit about which one we intend to use.
67 Subclassing an imported class
68
69 Output:
70 Adding a class to a Package Consider a package which has already one class. The package p1 contains one public class- ClassA . Now we need to add another class ClassZ in package p1. This can be done as follows: Define the ClassZ & make it public. Place the package declaration as first statement: package p1; Package p1; Public class ClassZ { // body of ClassZ }
71 Store this as ClassZ.java in directory / folder p1 . Compile ClassZ.java . It produces ClassZ.class file and this .class file also keep in the directory / folder p1.
72 Hiding classes When we import a package as: import p1.* , all public classes of package P1 are imported. If we are not willing to import (or want to hide) certain classes from outside of the classes then declare them “not public”. Exapmle package p1; public class A // public class available outside { //body of A } class B //not public, hidden { //body of B } Here, class B is not declared public , so it is hidden from outside of the package p1. this class can be used and seen only by other classes of the same package.