Can you overload constructor java

Java Guides

In this article, we will learn what is constructor overloading with example and how to use this keyword to call one constructor from another constructor of the same class.

In addition to overloading normal methods, you can also overload constructor methods. In fact, for most real-world classes that you create, overloaded constructors will be the norm, not the exception.

A default constructor is useful for creating objects with a default initialization value. When you want to initialize the objects with different values in different instantiations, you can pass them as the arguments to constructors. And yes, you can have multiple constructors in a class — which is constructor overloading.

Overloading Constructors Example

class Box < double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) < width = w; height = h; depth = d; > // compute and return volume double volume() < return width * height * depth; > >

As you can see, the Box(double w, double h, double d) constructor requires three parameters. This means that all declarations of Box objects must pass three arguments to the Box(double w, double h, double d) constructor. For example, the following statement is currently invalid and gives compiler error:

Читайте также:  Как использовать свой шрифт css

Since Box( ) requires three arguments, it’s an error to call it without them. This raises some important questions. What if you simply wanted a box and did not care (or know) what its initial dimensions were? Or, what if you want to be able to initialize a cube by specifying only one value that would be used for all three dimensions? As the Box class is currently written, these other options are not available to you.

Fortunately, the solution to these problems is quite easy: simply overload the Box constructor so that it handles the situations just described.

package com.javaguides.corejava.basics.polymorphism; public class OverloadingConstructors < public static void main(String[] args) < // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); > > /* * Here, Box defines three constructors to initialize the dimensions of a box * various ways. */ class Box < double width; double height; double depth; // constructor used when all dimensions specified Box(double w, double h, double d) < width = w; height = h; depth = d; > // constructor used when no dimensions specified Box() < width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box > // constructor used when cube is created Box(double len) < width = height = depth = len; > // compute and return volume double volume() < return width * height * depth; > >
Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0 

As you can see, the proper overloaded constructor is called based upon the parameters specified when new is executed.

Читайте также:  Java map add all values

Using this keyword — invoke one constructor from another constructor

Use the explicit this qualifier when accessing fields inside instance methods or constructors to avoid ambiguity in referring to variable names.

package com.javaguides.corejava.basics.polymorphism; public class OverloadingConstructors < public static void main(String[] s) < System.out.println(new Circle()); System.out.println(new Circle(50, 100)); System.out.println(new Circle(25, 50, 5)); > > class Circle < private int xPos; private int yPos; private int radius; // three overloaded constructors for Circle public Circle(int x, int y, int r) < xPos = x; yPos = y; radius = r; > public Circle(int x, int y) < xPos = x; yPos = y; radius = 10; // default radius > public Circle() < xPos = 20; // assume some default values for xPos and yPos yPos = 20; radius = 10; // default radius > public String toString() < return "center = (" + xPos + "," + yPos + ") and radius = " + radius; > >
center = (20,20) and radius = 10 center = (50,100) and radius = 10 center = (25,50) and radius = 5 

As you can see, the compiler has resolved the constructor calls depending on the number of arguments. Did you notice that you are duplicating the code inside the three constructors? To avoid that code duplication—and reduce your typing effort—you can invoke one constructor from another constructor. Of the three constructors, the constructor taking x-position, y-position, and a radius is the most general constructor. The other two constructors can be rewritten in terms of calling the three argument constructors, like so:

package com.javaguides.corejava.basics.polymorphism; public class OverloadingConstructors < public static void main(String[] s) < System.out.println(new Circle()); System.out.println(new Circle(50, 100)); System.out.println(new Circle(25, 50, 5)); > > class Circle < private int xPos; private int yPos; private int radius; public Circle(int x, int y, int r) < xPos = x; yPos = y; radius = r; > public Circle(int x, int y) < this(x, y, 10); // passing default radius 10 > public Circle() < this(20, 20, 10); // assume some default values for xPos, yPos and radius > public String toString() < return "center = (" + xPos + "," + yPos + ") and radius = " + radius; > >
center = (20,20) and radius = 10 center = (50,100) and radius = 10 center = (25,50) and radius = 5 

The output is exactly the same as for the previous program, but this program is shorter; you used this keyword to call one constructor from another constructor of the same class.

Источник

Can you overload constructor java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

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. For e.g. Vector class has 4 types of constructors. If you do not want to specify the initial capacity and capacity increment then you can simply use default constructor of Vector class like this Vector v = new Vector(); however if you need to specify the capacity and increment then you call the parameterized constructor of Vector class with two int arguments like this: Vector v= new Vector(10, 5);

constructor overloading

You must have understood the purpose of constructor overloading. Lets see how to overload a constructor with the help of following java program.

Constructor Overloading Example

Here we are creating two objects of class StudentData . One is with default constructor and another one using parameterized constructor. Both the constructors have different initialization code, similarly you can create any number of constructors with different-2 initialization codes for different-2 purposes.
StudentData.java

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; >//Getter and setter methods 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

Let’s understand the role of this () in constructor overloading

public class OverloadingExample2 < private int rollNum; OverloadingExample2() < rollNum =100; >OverloadingExample2(int rnum) < this(); /*this() is used for calling the default * constructor from parameterized constructor. * It should always be the first statement * inside constructor body. */ rollNum = rollNum+ rnum; >public int getRollNum() < return rollNum; >public void setRollNum(int rollNum) < this.rollNum = rollNum; >public static void main(String args[]) < OverloadingExample2 obj = new OverloadingExample2(12); System.out.println(obj.getRollNum()); >>

As you can see in the above program that we called the parameterized constructor during object creation. Since we have this() placed in parameterized constructor, the default constructor got invoked from it and initialized the variable rollNum .

Test your skills – Guess the output of the following program

public class OverloadingExample2 < private int rollNum; OverloadingExample2() < rollNum =100; >OverloadingExample2(int rnum) < rollNum = rollNum+ rnum; this(); >public int getRollNum() < return rollNum; >public void setRollNum(int rollNum) < this.rollNum = rollNum; >public static void main(String args[]) < OverloadingExample2 obj = new OverloadingExample2(12); System.out.println(obj.getRollNum()); >>
Exception in thread "main" java.lang.Error: Unresolved compilation problem:Constructor call must be the first statement in a constructor

Program gave a compilation error. Reason: this() should be the first statement inside a constructor.

Another Constructor overloading Example

Another important point to note while overloading a constructor is: When we don’t implement any constructor, the java compiler inserts the default constructor into our code during compilation, however if we implement any constructor then compiler doesn’t do it. See the example below.

public class Demo < private int rollNum; //We are not defining a no-arg constructor here Demo(int rnum) < rollNum = rollNum+ rnum; >//Getter and Setter methods public static void main(String args[]) < //This statement would invoke no-arg constructor Demo obj = new Demo(); >>
Exception in thread "main" java.lang.Error: Unresolved compilation problem:The constructor Demo() is undefined

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Оцените статью