User defined constructor in java

Constructors in Java

A constructor is a special method that is used to initialize an object. Every class has a constructor either implicitly or explicitly.

If we don’t declare a constructor in the class then JVM builds a default constructor for that class. This is known as default constructor.

A constructor has same name as the class name in which it is declared. Constructor must have no explicit return type. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.

Syntax to declare constructor

className is the name of class, as constructor name is same as class name.

parameter-list is optional, because constructors can be parameterize and non-parameterize as well.

Constructor Example

In Java, constructor structurally looks like given in below program. A Car class has a constructor that provides values to instance variables.

Types of Constructor

Java Supports two types of constructors:

Each time a new object is created at least one constructor will be invoked.

Car c = new Car() //Default constructor invoked Car c = new Car(name); //Parameterized constructor invoked

Default Constructor

In Java, a constructor is said to be default constructor if it does not have any parameter. Default constructor can be either user defined or provided by JVM.

If a class does not contain any constructor then during runtime JVM generates a default constructor which is known as system define default constructor.

If a class contain a constructor with no parameter then it is known as default constructor defined by user. In this case JVM does not create default constructor.

The purpose of creating constructor is to initialize states of an object.

The below image shows how JVM adds a constructor to the class during runtime.

default-constructor

User Define Default Constructor

Constructor which is defined in the class by the programmer is known as user-defined default constructor.

In this example, we are creating a constructor that has same name as the class name.

 class AddDemo1 < AddDemo1() < int a=10; int b=5; int c; c=a+b; System.out.println("*****Default Constructor*****"); System.out.println("Total of 10 + 5 output"> default-constructor

Constructor Overloading

Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters. Constructor overloading is not much different than method overloading. In case of method overloading you have multiple methods with same name but different signature, whereas in Constructor overloading you have multiple constructor with different signature but only difference is that constructor doesn't have return type.


Example of constructor overloading

class Cricketer < String name; String team; int age; Cricketer () //default constructor. < name =""; team =""; age = 0; >Cricketer(String n, String t, int a) //constructor overloaded < name = n; team = t; age = a; >Cricketer (Cricketer ckt) //constructor similar to copy constructor of c++ < name = ckt.name; team = ckt.team; age = ckt.age; >public String toString() < return "this is " + name + " of "+team; >> Class test: < public static void main (String[] args) < Cricketer c1 = new Cricketer(); Cricketer c2 = new Cricketer("sachin", "India", 32); Cricketer c3 = new Cricketer(c2 ); System.out.println(c2); System.out.println(c3); c1.name = "Virat"; c1.team= "India"; c1.age = 32; System .out. print in (c1); >>

this is sachin of india this is sachin of india this is virat of india

Constructor Chaining

Constructor chaining is a process of calling one constructor from another constructor in the same class. Since constructor can only be called from another constructor, constructor chaining is used for this purpose.

To call constructor from another constructor this keyword is used. This keyword is used to refer current object.

Lets see an example to understand constructor chaining.

 class Test < Test() < this(10); >Test(int x) < System.out.println("x output">x=10

Constructor chaining is used when we want to perform multiple tasks by creating a single object of the class.

In the below image, we have described the flow of constructor calling in the same class.

constructor-chaining

Example:

Lets see one more example to understand the constructor chaining. Here we have created three constructors and calling them using by using this keyword.

 class abc < public abc() < this(5); System.out.println("Default Constructor"); >public abc(int x) < this(5, 6); System.out.println("Constructor with one Parameter"); System.out.println("Value of x ==>"+x); > public abc(int x, int y) < System.out.println("Constructor with two Parameter"); System.out.println("Value of x and y ==>"+x+" "+y); > > class ChainingDemo1 < public static void main(String as[]) < abcobj = new abc(); >> 

output-constructor-chaining

Private Constructors

In Java, we can create private constructor to prevent class being instantiate. It means by declaring a private constructor, it restricts to create object of that class.

Private constructors are used to create singleton class. A class which can have only single object known as singleton class.

In private constructor, only one object can be created and the object is created within the class and also all the methods are static. An object can not be created if a private constructor is present inside a class. A class which have a private constructor and all the methods are static then it is called Utility class.

 final class abc < private abc() <>public static void add(int a, int b) < int z = a+b; System.out.println("Addition: "+z); >public static void sub(int x, int y) < int z = x-y; System.out.println("Subtraction: "+z); >> class PrivateConDemo < public static void main(String as[]) < abc.add(4, 5); abc.sub(5, 3); >> 

Источник

Providing Constructors for Your Classes

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear)

To create a new Bicycle object called myBike , a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike .

Both constructors could have been declared in Bicycle because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object , which does have a no-argument constructor.

You can use a superclass constructor yourself. The MountainBike class at the beginning of this lesson did just that. This will be discussed later, in the lesson on interfaces and inheritance.

You can use access modifiers in a constructor's declaration to control which other classes can call the constructor.

Источник

Java Constructors

Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.

What are Constructors in Java?

In Java, Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

Example

Java

Note: It is not necessary to write a constructor for a class. It is because the java compiler creates a default constructor (constructor with no arguments) if your class doesn’t have any.

How Java Constructors are Different From Java Methods?

  • Constructors must have the same name as the class within which it is defined it is not necessary for the method in Java.
  • Constructors do not return any type while method(s) have the return type or void if does not return any value.
  • Constructors are called only once at the time of Object creation while method(s) can be called any number of times.

Now let us come up with the syntax for the constructor being invoked at the time of object or instance creation.

class Geek < . // A Constructor Geek() < >. > // We can create an object of the above class // using the below statement. This statement // calls above constructor. Geek obj = new Geek();

The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an overloaded constructor), if you don’t type in the call to super in your constructor the compiler will provide you with a non-argument call to super at the first line of your code, the super constructor must be called to create an object:

If you think your class is not a subclass it actually is, every class in Java is the subclass of a class object even if you don’t say extends object in your class definition.

Need of Constructors in Java

Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions? The answer is No.
So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

When Constructor is called?

Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. Rules for writing constructors are as follows:

  • The constructor(s) of a class must have the same name as the class name in which it resides.
  • A constructor in Java can not be abstract, final, static, or Synchronized.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

So by far, we have learned constructors are used to initialize the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.

Types of Constructors in Java

Now is the correct time to discuss the types of the constructor, so primarily there are three types of constructors in Java are mentioned below:

1. Default Constructor in Java

A constructor that has no parameters is known as default the constructor. A default constructor is invisible. And if we write a constructor with no arguments, the compiler does not create a default constructor. It is taken out. It is being overloaded and called a parameterized constructor. The default constructor changed into the parameterized constructor. But Parameterized constructor can’t change the default constructor.

Источник

Читайте также:  Copying file with java
Оцените статью