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?
The important difference between constructors and methods is that constructors initialize objects that are being created with the new
operator, while methods perform operations on objects that already exist.
Constructors can't be called directly; they are called implicitly when the new
keyword creates an object. Methods can be called directly on an object that has already been created with new
.
The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public
), and they have method bodies in braces.
Constructors must be named with the same name as the class name. They can't return anything, even void
(the object itself is the implicit return).
Methods must be declared to return something, although it can be void
.
new
keyword to call a constructor & create an object. Inside a constructor, it can refer to calling a different or superclass constructor via the this()
or super()
syntax, sometimes with arguments. –
Boyce 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.
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...
Constructors must be invoked with the
new
operator while methods may not be invoked with thenew
operator. Related: Constructors may not be called by name while methods must be called by name.Constructors may not have a return type while methods must have a return type.
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 }
Constructors may initialize instance constants while methods may not.
Public and protected constructors are not inherited while public and protected methods are inherited.
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?
They both have parameter lists.
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.
Constructors may be: private, protected, public.
Methods may be: private, protected, public, abstract, static, final, synchronized, native, strictfp.
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.
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.
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.
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 difference r
:
- Constructor must have the name same as class but method can be made by any name.
- Constructor are not inherited automatically by child classes while child inherit method from their parent class unless they r protected by private keyword.
- Constructor
r
called explicitly while methods implicitaly. - Constructor doesnot have any return type while method have.
Constructor cannot inherited by child classes
is very important distinction vs Methods. –
Ardoin Constructor in type..; only public, protected & private are permitted
, so they cannot be abstract, final, native, static, or synchronized. –
Ardoin 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.
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");
}
}
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
Here are some main key differences between constructor and method in java
- Constructors are called at the time of object creation automatically. But methods are not called during the time of object creation automatically.
- Constructor name must be same as the class name. Method has no such protocol.
- 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
© 2022 - 2024 — McMap. All rights reserved.