Skip to content

Commit 4321ac4

Browse files
committed
feat: The difference between a constructor and a method in Java is fundamental in object-oriented programming.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 52fbb53 commit 4321ac4

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed
Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ The difference between a constructor and a method in Java is fundamental in obje
22

33
Let's break down the key differences:
44

5-
1. Purpose
5+
1. Purpose:
66
- Constructor:
77
- A constructor is used to initialize a new object. It is called when an object is created.
88
- Its main role is to set up the initial state of the object, such as initializing fields or setting up resources.
@@ -11,7 +11,7 @@ Let's break down the key differences:
1111
- A method is used to define behavior or operations that an object can perform.
1212
It can be called after the object is created to perform actions on the object.
1313

14-
2. Name
14+
2. Name:
1515
- Constructor:
1616
- The constructor's name must be the same as the class name.
1717
- For example, in the `Arithmetic` class, the constructor must be named `Arithmetic`.
@@ -20,7 +20,7 @@ Let's break down the key differences:
2020
- A method can have any name (except it cannot be the same as the class name, unless it's a constructor).
2121
- For example, a method can be named `add`, `multiply`, or `display`.
2222

23-
3. Return Type
23+
3. Return Type:
2424
- Constructor:
2525
- A constructor does not have a return type. It doesn't return anything, not even `void`.
2626

@@ -34,8 +34,7 @@ Let's break down the key differences:
3434
- Example:
3535
public int add(int a, int b) { ... }
3636

37-
4. Invocation
38-
37+
4. Invocation:
3938
- Constructor:
4039
- A constructor is automatically called when you **create an object** using the `new` keyword.
4140

@@ -49,7 +48,6 @@ Let's break down the key differences:
4948
int sum = obj.add(10, 20); // Calling the add method
5049

5150
5. Parameters:
52-
5351
- Constructor:
5452
- Constructors can take parameters, allowing you to pass values to initialize the object at the time of creation.
5553

@@ -60,7 +58,6 @@ Let's break down the key differences:
6058

6159
- Method:
6260
- Methods can also take parameters, but they are called after the object is created.
63-
6461
- Example:
6562
public int add(int a, int b) {
6663
return a + b;
@@ -128,7 +125,7 @@ class Car {
128125

129126
public class Main {
130127
public static void main(String[] args) {
131-
// Creating a new object of type Car
128+
// Creating a new object of type Car.
132129
Car myCar = new Car("Tesla Model 3", 2021); // Constructor is called here
133130

134131
// Calling the method to display car details

0 commit comments

Comments
 (0)