[java] Methods vs Constructors in Java

I have just started programming with Java. The text we use is lacking when talking about methods and constructors. I'm not sure what a method or a constructor is exactly and what makes each unique. Can someone please help me define them and differentiate between the two?

This question is related to java methods constructor

The answer is


A constructor is a special kind of method that allows you to create a new instance of a class. It concerns itself with initialization logic.


the difference r:

  1. Constructor must have the name same as class but method can be made by any name.
  2. Constructor are not inherited automatically by child classes while child inherit method from their parent class unless they r protected by private keyword.
  3. Constructor r called explicitly while methods implicitaly.
  4. Constructor doesnot have any return type while method have.

Constructor is special function used to initialise the data member, where the methods are functions to perform specific task.

Constructor name is the same name as the class name, where the method name may or may not or be class name.

Constructor does not allow any return type, where methods allow return type.



Constructor typically is Method.

When we create object of a class new operator use then we invoked a special kind of method called constructor.

Constructor used to perform initialization of instance variable.

Code:

public class Diff{

public Diff() { //same as class name so constructor 

        String A = "Local variable A in Constructor:";
        System.out.println(A+ "Contructor Print me");
    }
   public void Print(){
        String B = "Local variable B in Method";
        System.out.println(B+ "Method print me");
    } 


    public static void main(String args[]){
        Diff ob = new Diff();

        }
}

`

  • Output:

    Local variable A in Constructor:Contructor Print me

So,only show here Constructor method Diff() statement because we create Diff class object. In that case constructor always come first to instantiate Class here class Diff().

typically,

Constructor is set up feature.

Everything start with here, when we call ob object in the main method constructor takes this class and create copy and it's load into the " Java Virtual Machine Class loader " .

This class loader takes this copy and load into memory,so we can now use it by referencing.

Constructor done its work then Method are come and done its real implementation.

In this program when we call

ob.print();

then method will coming.

Thanks

Arindam


A "method" is a "subroutine" is a "procedure" is a "function" is a "subprogram" is a ... The same concept goes under many different names, but basically is a named segment of code that you can "call" from some other code. Generally the code is neatly packaged somehow, with a "header" of some sort which gives its name and parameters and a "body" set off by BEGIN & END or { & } or some such.

A "consrtructor" is a special form of method whose purpose is to initialize an instance of a class or structure.

In Java a method's header is <qualifiers> <return type> <method name> ( <parameter type 1> <parameter name 1>, <parameter type 2> <parameter name 2>, ...) <exceptions> and a method body is bracketed by {}.

And you can tell a constructor from other methods because the constructor has the class name for its <method name> and has no declared <return type>.

(In Java, of course, you create a new class instance with the new operator -- new <class name> ( <parameter list> ).)


The Major difference is Given Below -

1: Constructor must have same name as the class name while this is not the case of methods

class Calendar{
    int year = 0;
    int month= 0;

    //constructor
    public Calendar(int year, int month){
        this.year = year;
        this.month = month;
        System.out.println("Demo Constructor");
    }

    //Method
    public void Display(){

        System.out.println("Demo method");
    }
} 

2: Constructor initializes objects of a class whereas method does not. Methods performs operations on objects that already exist. In other words, to call a method we need an object of the class.

public class Program {

    public static void main(String[] args) {

        //constructor will be called on object creation
        Calendar ins =  new Calendar(25, 5);

        //Methods will be called on object created
        ins.Display();

    }

}

3: Constructor does not have return type but a method must have a return type

class Calendar{

    //constructor – no return type
    public Calendar(int year, int month){

    }

    //Method have void return type
    public void Display(){

        System.out.println("Demo method");
    }
} 

Here are some main key differences between constructor and method in java

  1. Constructors are called at the time of object creation automatically. But methods are not called during the time of object creation automatically.
  2. Constructor name must be same as the class name. Method has no such protocol.
  3. The constructors can’t have any return type. Not even void. But methods can have a return type and also void. Click to know details - Difference between constructor and method in Java

In Java, classes you write are Objects. Constructors construct those objects. For example if I have an Apple.class like so:

public class Apple {
    //instance variables
    String type; // macintosh, green, red, ...

    /**
     * This is the default constructor that gets called when you use
     * Apple a = new Apple(); which creates an Apple object named a.
     */

    public Apple() {
        // in here you initialize instance variables, and sometimes but rarely
        // do other functionality (at least with basic objects)
        this.type = "macintosh"; // the 'this' keyword refers to 'this' object. so this.type refers to Apple's 'type' instance variable.
    }

    /**
     * this is another constructor with a parameter. You can have more than one
     * constructor as long as they have different parameters. It creates an Apple
     * object when called using Apple a = new Apple("someAppleType");
     */
    public Apple(String t) {
        // when the constructor is called (i.e new Apple() ) this code is executed
        this.type = t;
    }

    /**
     * methods in a class are functions. They are whatever functionality needed
     * for the object
     */
    public String someAppleRelatedMethod(){
        return "hello, Apple class!";
    }

    public static void main(String[] args) {
        // construct an apple
        Apple a = new Apple("green");
        // 'a' is now an Apple object and has all the methods and
        // variables of the Apple class.
        // To use a method from 'a':
        String temp = a.someAppleRelatedMethod();
        System.out.println(temp);
        System.out.println("a's type is " + a.type);
    }
}

Hopefully I explained everything in the comments of the code, but here is a summary: Constructors 'construct' an object of type of the class. The constructor must be named the same thing as the class. They are mostly used for initializing instance varibales Methods are functionality of the objects.


Other instructors and teaching assistants occasionally tell me that constructors are specialized methods. I always argue that in Java constructors are NOT specialized methods.

If constructors were methods at all, I would expect them to have the same abilities as methods. That they would at least be similar in more ways than they are different.

How are constructors different than methods? Let me count the ways...

  1. Constructors must be invoked with the new operator while methods may not be invoked with the new operator. Related: Constructors may not be called by name while methods must be called by name.

  2. Constructors may not have a return type while methods must have a return type.

  3. If a method has the same name as the class, it must have a return type. Otherwise, it is a constructor. The fact that you can have two MyClass() signatures in the same class definition which are treated differently should convince all that constructors and methods are different entities:

    public class MyClass {
       public MyClass() { }                                   // constructor
       public String MyClass() { return "MyClass() method"; } // method
    }
    
  4. Constructors may initialize instance constants while methods may not.

  5. Public and protected constructors are not inherited while public and protected methods are inherited.

  6. Constructors may call the constructors of the super class or same class while methods may not call either super() or this().

So, what is similar about methods and constructors?

  1. They both have parameter lists.

  2. They both have blocks of code that will be executed when that block is either called directly (methods) or invoked via new (constructors).

As for constructors and methods having the same visibility modifiers... fields and methods have more visibility modifiers in common.

  1. Constructors may be: private, protected, public.

  2. Methods may be: private, protected, public, abstract, static, final, synchronized, native, strictfp.

  3. Data fields may be: private, protected, public, static, final, transient, volatile.

In Conclusion

In Java, the form and function of constructors is significantly different than for methods. Thus, calling them specialized methods actually makes it harder for new programmers to learn the differences. They are much more different than similar and learning them as different entities is critical in Java.

I do recognize that Java is different than other languages in this regard, namely C++, where the concept of specialized methods originates and is supported by the language rules. But, in Java, constructors are not methods at all, much less specialized methods.

Even javadoc recognizes the differences between constructors and methods outweigh the similarities; and provides a separate section for constructors.


The main difference is

1.Constructor are used to initialize the state of object,where as method is expose the behaviour of object.

2.Constructor must not have return type where as method must have return type.

3.Constructor name same as the class name where as method may or may not the same class name.

4.Constructor invoke implicitly where as method invoke explicitly.

5.Constructor compiler provide default constructor where as method compiler does't provide.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items

Examples related to constructor

Two constructors Class constructor type in typescript? ReactJS: Warning: setState(...): Cannot update during an existing state transition Inheritance with base class constructor with parameters What is the difference between using constructor vs getInitialState in React / React Native? Getting error: ISO C++ forbids declaration of with no type undefined reference to 'vtable for class' constructor Call asynchronous method in constructor? Purpose of a constructor in Java? __init__() missing 1 required positional argument