Difference between Constructor and Method in Java
What is Constructor?
In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to instantiate and initialize objects. A constructor must have the same name as the class; for example, the Constructor of the string class is called string, and the Constructor of the point class is called point. Also, the Constructor of the circle class we created is called a circle.
The Constructor doesn't have any return type. Also, constructors are invoked or reached using the new operator, and we use constructors to give initial values to the attributes of our object. Finally, a default constructor is a zero-argument constructor with an empty body, so it is a constructor that does not take any parameters and does not do anything. We can use it to create an object from the class.
Now let's consider the same class as before, representing a circle. It has the following attributes and the following methods.
- Data Fields (attributes)
- Center: Point
- Radius: double
- Methods(actions)
- Methods (actions)
- Circle (initialCenter : Point ,initial : double)
- getArea(): Double
- getPerimeter() : Double
- setRadius (newRadius : double): void
- setCenter (newCenter :point):void
The following attributes and methods now we want to add this Constructor it is call circle because the name of the class is a circle, this Constructor is going to take two parameters the first parameter is a point. We will call it the initial centre, and the second parameter is a double, and we will call it the initial radius. So now, when we create circle objects, we can give the Constructor two arguments, a point and a double.
We will initialize the values of our attributes with these values passed over here, so our centre attribute will be equal to the initial centre and our radius attribute will be similar to the initial radius, so let's create this Constructor first.
class Circle {
Point center;
double radius;
Circle(Point initialCenter, double initialRadius){
center = initialCenter;
radius = initialRadius;
}
Explanation:-
In the above expression, the circle class has these two attributes, and now we have a method called a circle. It does not have a return type; this method takes a point initial centre and a double initial radius. Inside this method, we assign the centre attribute equal to this initial centre and the radius equal to the initial radius, so this is our Constructor. You are using it to initialize the values of the attributes, as you can see, so now let's use this Constructor to create circle objects.
Initialize Circle Objects
public static void main(String[] args){
Circle c1 = new Circle(new Point(1,2),3);
System.out.println(c1.center); //java.awt.Point[x=1,y=2]
System.out.println(c1.radius); //3.0
}
Explanation:-
please have a look at this in the above code inside the primary methods, we were creating a circle c1 which is equal to a new circle, and over here, we are passing two arguments, so we were calling the Constructor that is called a circle and takes two arguments; the first argument is a point with x equal one and y equal two and the second argument is an integer, of course, this value will be cast to a double because the second argument is a double, so now we were printing the centre of the circle c1, and this will be the output (3.0). as we can use constructors to initialize the attributes of our object; in other words, we use them to initialize our objects.
Using the default constructor
Public static void main(String[] args){
Circle c1 = new Circle();
}
Explanation:-
In the above code here, we are creating a circle c1 equal to a new circle; here, we have an error that says expected two arguments but found zero, so our circle class no longer has a default constructor. It only has the Constructor that takes two arguments; when no constructors are created, a default constructor is created automatically by java, but when we create a constructor, the default constructor is not completed; in other words, if we want a zero-argument constructor, then we have to make it.
Overloading Circle
Class Circle{
Point centre;
Double radius;
Circle(){}
Circle(Point initialCenter,doubleinitialRadius){
center= initialCenter;
radius=initialRadius;
}
Explanation:-
Now we are creating two constructors, so we are overloading the Constructor. The first Constructor doesn't take any parameters, and it does nothing. It has an empty body, and the second Constructor is the same as before. So now we have two ways to create circle objects. The first one is using this Constructor; in this case, the value of the centre and the radius will be default values.
The centre will be null, and the radius will be zero, and the second way is using this Constructor. In this case, the importance of the centre and the radius will be given by the user now; let's modify this Constructor over here; let's suppose that when we use this Constructor, we want to provide default values for the centre and the radius other than null and zero so now look following code.
class Circle {
Point centre;
Double radius;
Circle(){
Center = new Point(0,0);
Radius = 1;
}
Circle(Point initialCenter,doubleinitialRadius){
center = initialCenter;
radius = initialRadius;
}
…
}
In above, inside this Constructor, we are assigning the centre to be equal to a new point with x equal to zero and y equal to zero; also, we are giving the radius to be similar to one, so now if we use this Constructor to create a circle object, the centre will be equal to this point, and the radius will be similar to 1. If the user does not want to give a value for the centre and the radius, he can use this Constructor, and we will provide default values, as we can see. So now, let's create circle objects using both of these constructors.
Methods
In the method, we will discuss Void methods, value-returning method and we will see return keyword and finally, we will call some ways.
Void method
It is a method that does not return a value. In other words, the return type of the method is void. This is an example of a void method.
public static void sayHi(){
System.out.println(“Hi”);
}
Now we have to understand how we can write a method in java; first of all, we will use the public keyword to make this method a public method and previously, we saw that a public method could be accessed from outside the class, and after that, we will use the static keyword and using the static keyword, we will able to call this method from inside the primary method.
So at this point, we will always use the public and static keywords, and later on, in object-oriented programming, we will start using other keywords over here; now, after that, we have the type of the method. In this case, this method is a void method, so the type is void; in other words, this method does not return a value, and immediately after that, we have the technique's name. This method is called hi; then we have empty parentheses, so this method does not take parameters; now, all this over here is called the header of the method.
It contains some modifiers, the type, the name, and the parameters of the method. After that, we have the method's body where we will write the code that will be executed when we call this method. In other words, this is the block of regulation of the method, so in this case, we are printing the string using the println method. Let's see how we can call the say hi method.
public static void main (String[] args){
System.out.println(“message1”);
sayHi
System.out.println(“message2”);
}
public static void sayHi(){
System.out.println(“Hi”);
}
In the above code, the starting point of execution is the main method, so inside the main method, we are printing message 1. So, first of all, we will see message 1 printed, and after that, we are calling the say hi method, so the main method will stop executing at this point and complete the say hi method. So we are goingto perform the body of this method, so we are going to print the string hi so we will see how we printed and after we are finished running this method, so we will continue to exit the main method from this point ( in above code sayHi), so we are going to print message 2so we will see message 2 printed so this is the output of the above program.
(message1
Hi
Message2)
Let's see another example. We have the same code but over here.
public static void main (String[] args){
System.out.println(“message1”);
sayHi(“hello”);
System.out.println(“message2”);
}
public static void sayHi(){
System.out.println(“Hi”);
}
We are passing a parameter to the sayHi method, so in this case, we will get an error because, as we can see over here, this method does not take any parameter, so if we try to give it a parameter, who will get an error, now we discuss value-returning methods.
Value-Returning Method
A Value returning is a method that returns a value, and the return type of this method is the type of data that will be returned. Let's see an example.
public static int sum(int x, int y){
int sum =x + y;
return sum;
}
Explanation:-
Here in the above example, we have a method public static, and the type is an integer, so this method should return an integer. This method is called sum, and it takes two parameters, so let's see how we can give a method some parameters; in this case, I want to share this method with two integers, so, first of all, we will declare the first integer, so we are saying int x. We will put a comma, and after that, we will display the second integer, so now the method sum takes two integers the first one is called X, and the second one is called Y; of course, we can give other names to these variables.
For example, we can't call this variable l and call this variable j whatever you want what's essential is that names of these variables should be valid identifiers, so now we said before the parameters are local variables so we can use the variable x and the variable Y in the body of the method. So over here, we are declaring a third integer called sum, which is also a local variable. We are initializing the sum to be equal to X plus y, so I am getting the value of x and the value of Y, which will be passed as parameters. We are adding them and storing the value inside the sum.
After that, to return some data from this method, we will use the return keyword in the case I'm saying return sum so the value inside so the variable sum will be returned by this method so, later on, we canaccess this value. We can do whatever we want with this value; for example, we can print it or store it inside a variable; now, let's look at another way of writing this method. Please have a look at this code over here. We have the same header. Still, inside the method returning x plus y immediately, I'm not using a third variable, so this expression over here will be calculated. Then the result of X plus y will be returned by this method. Now we try to call the sum method.
CALLING SUM
public static void main(String[] args){
System.out.println(“message1”);
Sum(1,2);
System.out.println(“message2”);
}
x=1,y=2
public static int sum(int x, int y){
return x + y;
}
Output:
Message1
Message2
Explanation:-
In above code here our primary method we are printing message one So message one will be printed and after that we are calling the sum method we are passing one as a parameter and then a comma and then we have two so what will happen over here you can imagine the following we will assign X to be equal to 1 and Y to be similar to 2 so the first parameter will be put inside X and the second parameter will be put inside Y so the order of the parameter is important and also the type of the parameters is necessary because X is an integer and Y is an integer we have to give integers over here and as you can see 1& 2 are integers so when we call this method X will be equal to 1 and Y will be similar to 2 and after that inside the method we are returning X plus y so 1 plus 2 is equal to 3 so 3 will be replaced by this method so you can imagine that over here now we have the value 3 but you are not doing anything with this value so nothing will happen so now we are done executing our sum method so we'll continue running the main method so we will print messages 2 and message 2 will be published. Let's see another example.
public static void main(String[] args){
System.out.println(“message1”);
Sum(1,2);
System.out.println(“message2”);
}
public static int sum(int x, int y){
return x + y;
}
Output:
message1
3
message2
We have the same code, but now I'm printing the sum of 1 & 2, so over here, we are going to return 1 plus 2, which is equal to 3, so we will have 3 over here, and after that, we are printing 3 , so we are printing the
return value of the sum method so, first of all, we print message 1, and then we will print 3 and finally we will print message two, so over have we are using the return value we are printing it using the println method. Still, previously we were not doing anything with the return value. Let's see another example.
public static void main(String[] args){ System.out.preintln(“message1”);
System.out.println(sum(1,2)+ sum(3,5));
System.out.println(“message2);
}
public static int sum(int x, int y){
return x+y;
}
Output:
message1
11
Message2
In the above example, we are first printing a message1. After we are printing the sum of 1 & 2 plus the sum of 3 & 5, so I am adding the return value of this method with the return value of this method, so over here, we have 1 plus 2, which is equal to 3 added to 3 plus 5 is equal to 8 so 3 plus 8 is equal to 11. and finally, we will print message2.
The Return Keyword
A keyword can be used to return a value from a method.
public static int sum(int x, int y){
return x + y;
}
In the above, just like we saw a little bit, we were returning X plus y, so the value of x plus y was produced from this method.
Let's see another example.
public static int sum(int x, int y){
return x + y;
}
public static void sayHi(){
System. out.println(“Hi”);
return;
In the above example, this is our method sayHi, we are printing Hi, and after that, we execute the return. As you can see, I am NOT returning a value; I am just using the return keyword followed by a semicolon, so what will happen over here when the return statement is executed? We will exit the method. We can see another example.
public static void sayHi(){
return;
System. out.println(“Hi”);
}
Public static int sum(int x, int y){
return x+y;
System .out.println(“Done”);
}
In the above example, suppose this is our sayHi method, so first of all, we are executing return. After that, we are printing Hi, so as I said, when the return statement is completed, we will exit the method, so whenever we call the sayHi way, the first thing that we will do is we will leave the method, so we will never execute this statement over here so this statement is unreachable .it will never be completed. Let's have a look at this example.
Here we are returning X plus y, and after that, I am printing "Done" the same thing will apply when the return statement is executed. We will exit the method, and we will return the value of x plus y, and this statement over here will never be completed, and this code over here, and this code will give us an error. It will say that 1st statement and 2nd statement are unreachable. Here is a question why do we want to use a return statement and avoid the method; suppose there is a condition, and if 1st condition is accurate, we want to exit a void method. Then, in this case, you will use the return keyword. Now we will see another example.
public static void sayHi(){
return 5;
}
public static int sum(int x, int y){
return “Done”;
}
Explanation:- In the above example, here we have the sayHi method, and its type is void, and inside that, we are returning five, so here we are replacing an integer, but the kind of this method is void, so this will give us a problem, we are producing a value that is not compatible with the type of this method and another example the type of this method is an integer, and we are returning a string, so the return type and the type of the data that we are replacing are not compatible so also this over here will give us an error.
Difference between Constructor and Method
Constructor | Method |
It is a block of code that initializes an object. | It is a collection of statements that returns a value upon execution. |
It can be used to initialize an object. | It consists of Java code which needs to be executed. |
It is invoked by using a new keyword. | Method calls invoke it. |
It doesn’t have any return type. | It must have a return type. |
It initializes an object that doesn't exist. | It does all the operations on an already existing object. |
It must have the same name as the class. | Its name can be anything. |
A class can have many constructors but not the same parameters. | A class can have many methods but no same parameters. |
A subclass cannot inherit a parent class constructor. | A subclass can inherit a method which belongs to the parent class. |
It is invoked implicitly by the system. | It is invoked manually by a programmer. |