Difference Between the Constructor and the Method in JavaAs we know that Java strictly follows the OOPs concepts. All the variables and methods must be presented in the classes. Java classes contain both the constructor and the method. Before understanding the difference between constructor and method, let's recall the constructor and method. ConstructorThe constructor and method both are different from each other. However, the constructor is used for initializing the object's state. Constructors can also contain data members and member functions in the same way as the method contains. The data members and member functions of the constructor are executed at the time of creating an object of that class. The new keyword plays an important role in creating an instance of the class. Let's take an example and understand how we can create an object of the class and call it the constructor of the class. ConstructorExample.java Output: MethodThe method is a block of code that is used for performing a particular task. It reduces the length and the repetitive code. It may or may not return a value to the caller. By creating a method, we can reuse the code without retyping the code. Let's take an example of a method to understand how we can create a method and use it in our class. MethodExample.java Output: Difference Between Constructor and MethodThe following table shows the key differences between constructor and method.
|
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India