2 constructors in one class java

Class With Multiple Constructors In Java

The constructor of a class is used to initialize the member variables and perform any other setup. Some times it is required to have multiple constructors to initialize the object in different ways. For e.g., one constructor could be used to initialize the student name and marks and another constructor can be used to initialize only the student name . Similar to Method Overloading In Java, this is called Constructor Overloading.

class TestMultipleConstructors
public static void main(String arg[])
Student yogesh = new Student("Yogesh", 67, 'B');
Student narayan = new Student("Narayan", 72);
Student mahesh = new Student("Mahesh");

System.out.println(yogesh.name + " belongs to section " + yogesh.section + " and got " + yogesh.marks + " marks.");
System.out.println(narayan.name + " belongs to section " + narayan.section + " and got " + narayan.marks + " marks.");
System.out.println(mahesh.name + " belongs to section " + mahesh.section + " and got " + mahesh.marks + " marks.");

>
>

class Student
String name;
int marks;
char section;

// CONSTRUCTOR 1
Student(String nameParam, int marksParam, char sectionParam)
name = nameParam;
marks = marksParam;
section = sectionParam;
>

// CONSTRUCTOR 2
Student(String nameParam, int marksParam)
name = nameParam;
marks = marksParam;
section = 'A';
>

// CONSTRUCTOR 3
Student(String nameParam)
name = nameParam;
marks = 0;
section = 'A';
>

>

Yogesh belongs to section B and got 67 marks.
Narayan belongs to section A and got 72 marks.
Mahesh belongs to section A and got 0 marks.

Here we have defined 3 constructors — CONSTRUCTOR 1 takes nameParam , marksParam and sectionParam as inputs, CONSTRUCTOR 2 takes nameParam and marksParam where as CONSTRUCTOR 3 takes only nameParam . Also note that CONSTRUCTOR 2 defaults section to ‘A’ and CONSTRUCTOR 3 defaults marks to 0 and section to ‘A’ . In the main class we have created students yogesh , narayan and mahesh using the three constructors and printed the student details. For printing the variables we have used the dot ( . ) operator.

  • Create one more student Srinath with 85 marks and in section ‘C’ and print his details.
  • Change the marks of mahesh to 90 and his section to ‘D’ and print his details. Use the dot( . ) operator to access the variables.

If we observe, in this program the parameters passed to the constructor are called nameParam , marksParam and sectionParam . It would be better we could call them name , marks and section since it will be easier for reading the program. This can be achieved by using this keyword. this keyword can also be used to reduce the duplicate code in the constructors. This is explained in this Keyword In Java.

Читайте также:  Html input type decimal

Источник

2 constructors in one class java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

A Guide to Constructor Chaining in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java Developer Tutorials

Constructor chaining refers to the ability to call a constructor inside another constructor. You can use a constructor chain either within the same class or even with another one. For the latter, the constructor should be through inheritance from the super class.

In this Java programming tutorial, you will learn the three ways in which you can carry out constructor chaining.

Java Constructor Chaining in the Same Class

You can create multiple constructors in the same class, each with a different number of arguments that it accepts. To call one of the constructors in another constructor (of the same class), use the keyword this().

If the constructor you are calling takes some arguments, then include them in the round brackets of this(). It is important for you to note that when using this() to call a constructor, it should always be the first statement in the calling constructor.

Читайте также:  Accessing objects in php

There also needs to be at least one constructor that does not use the statement this().

Consider the Java example below showing how to chain constructors in the same class:

public class ChainWithinClass < ChainWithinClass()< System.out.println("\nThis is the no-arg constructor."); >ChainWithinClass(int y) < this(); int var1 = y; System.out.println("You passed one argument: " + var1); >ChainWithinClass(int a, int b) < this(3); int var2 = a; int var3 = b; System.out.println("You passed two arguments: " + var2 + " and " + var3); >public static void main(String[] args) < ChainWithinClass chainObj = new ChainWithinClass(2,4); >>

Running this code will produce the following output:

This is the no-arg constructor. You passed one argument: 3 You passed two arguments: 2 and 4

The example shows how you can use three different constructors in the same class: one with no argument, one with only one argument, and the third with two arguments.

A very interesting point to consider in this example is how the constructors are called. It explains the order in which the messages are output on your screen.

When the arguments 2 and 4 are passed to ChainWithinClass() at instantiation, the constructor ChainWithinClass(int a, int b) is the first to be called.

Inside this constructor, the constructor ChainWithinClass(int y) is then called by this(3). Inside the body of ChainWithinClass(int y), the statement calling the no-arg constructor is the first to be run.

When the no-arg constructor is called, the message “This is the no-arg constructor.” is then printed out. After this, the remaining statements in ChainWithinClass(int y) are executed and then finally those of ChainWithinClass(int a, int b).

Before moving into the next section, note that the order in which the constructors appear in the class’ body does not influence the order in which they are run.

Constructor Chaining to Another Class in Java

As mentioned earlier, constructor chaining to another class happens through inheritance. The key point to note here is that the constructors in the super class are called before those of the sub class.

To call the constructors in the base class, simply use the statement super() in the constructor of the child class. Just like constructor chaining within the same class, the statement super() should always be the first one in the constructor of your subclass.

See the code below for an example of how to chain a constructor to another class in Java:

class Account < Account(String first_name, int your_age)< String fname = first_name; int age = your_age; System.out.println("\nThe name entered is " + fname); System.out.println("Your are " + age + " years old."); >Account() < System.out.println("\nWelcome dear customer"); >public static void main(String args[]) < FixedDeposit acct = new FixedDeposit(); >> class FixedDeposit extends Account < FixedDeposit()< super(); // calling the no-arg constructor in the base class double APY = 12.5; System.out.println("Your current interest rate is " + APY + "%"); >>

Running this code will produce the following output:

Welcome dear customer Your current interest rate is 12.5%

The above code shows how a subclass FixedDeposit calls the constructor in the superclass Account.

Читайте также:  Arrays and multidimensional arrays java

An interesting thing to note is that even though the statement super() was not explicitly included, the subclass constructor would have still invoked the super class’ no-arg constructor.

That said, this means that you will get a compiler error if your superclass doesn’t define a no-arg constructor, regardless of whether you did not use super().

If you have a parameterized constructor, you can avoid this by calling it. For this example, that is Account (String first_name, int your_age).

Simply pass the values through the round brackets in super():

Using an Initialization Block for Constructor Chaining in Java

Apart from using constructors to initialize values when a class is instantiated, you can also use an initialization block. The syntax is simple and merely consists of two curly brackets and the block of code in it:

Initialization blocks are used when you want certain statements to be executed in all the constructors you define. They are always the first to be executed in the constructor before the other code in it.

A key point to note is that initialization blocks are run in the order in which they appear in the class’ body.

class Apples < < System.out.println("\nThis is fresh from South Africa."); >Apples() < System.out.println("Color: Green"); > < System.out.println("No artificial fertilisers used!"); >Apples(String color) < System.out.println("Color: "+ color); >public static void main(String args[]) < Apples myApple = new Apples(); >>

Here is the expected output from running this code:

This is fresh from South Africa. No artificial fertilisers used! Color: Green

Summary of Constructor Chaining in Java

Constructor chaining provides you a similar utility to that provided by method overloading. It enables you to define multiple constructors and be able to call them using the same initialization. Constructor chaining ultimately simplifies how you initialize values.

Источник

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