Difference between method and constructor
The following are the difference between method and constructor.
- Method name may or may not be the same as the class name whereas the constructor name must be same as the class name.
- A method should have a return type in java where are constructor never returns any value, so it has no return type.
- A method can be declared as static, final, abstract whereas this 3 keyword is not allowed for the constructor.
- A method can be called by class name, object name or directly in Java whereas constructor name called by new, this and super keyword.
- Java support method overriding where as constructor never support overriding in java.
PROGRAM:-
class Test { Test() { System.out.println("constructor"); } static void Test() { System.out.println("method"); } public static void main(String[] args) { Test(); Test.Test(); Test t1=new Test(); t1.Test(); } };
O/P method
method
constructor
method
Example of the method is:-
class Test { int x=10; static void show() { System.out.println("I am in show method"); } public static void main(String[] args) { show(); //call directly Test.show(); //call by class name Test t=new Test(); //object creation t.show(); // call by object name } }
O/P I am in show method
I am in show method
I am in show method
Example of a constructor is
Class Test { Test(int x) { System.out.println(“I am in parameter constructor”); } public static void main(String[] args) { new Test(123); }
8 replies on “Difference between constructor and method”
Awesome! Its in fact amazing paragraph, I have got much clear idea regarding from this piece of
thank u
good stuff. I will make sure to bookmark your blog.
Thank U So much… also read another article and give feedback?
Awesome! Its in fact amazing paragraph, I have got much clear idea regarding from this piece of
Thank U
sound like you know what you?re talking about! Thanks
Thanks for giving the feedback