Urgenthomework logo
Live chat


Java Constructor Homework Help


A constructor is automatically called when a new instance of an object is created. A constructor is a special technique to initialize the objects. It is created with the same name as class name but it does't have any return type

For example :

{`public class MyClass1 {  ;
//This is the constructor with the same name.
MyClass1() {  ;
}  ;
}  ; `}

Types of constructors are used in java

  1. Default constructor: it is created by the java compiler itself when no constructor is found in the program. It is automatically placed during compilation.
  2. without argument constructor (No arg): constructor with without any arguments is called the no-arg constructor.
  3. with the argument (parameterized): constructor with the argument is called the parameterized constructor.

Rules for creating a constructor in java:

  • Constructor name must be same as class name
  • Must not have any return type
  • It can not be static and abstract

Difference between java method and constructor

Purpose: A constructor is used for initializing of object and java method is used to expose the behaviour of an object.

Return type: constructor does't have any return type but java method must have a return type.

Invoke method: constructor is invoked implicitly whereas java method is invoked explicitly.

Compiler: Java compiler can generate default constructor if no constructor is found in the program. But in the case of java method, method Is not provided by the java compiler.

Name: Constructor name must be same as the class name. but it not necessary in java method.

Copyright © 2009-2023 UrgentHomework.com, All right reserved.