DEV Community

Sadaf Khan
Sadaf Khan

Posted on

Post 3: Understanding Objects and Methods in Java

An object is an instance of a class, and it is used to call methods. In our previous post, Post 2: Understanding Methods in Java, we discussed methods. Now, we’ll show how to call those methods through objects.

Image description

In this example, the object and methods are created in two different classes:

  • The class where the methods are created is called First1.
  • The class where the object is created is called Second2.

Breakdown of First1 object1 = new First1();:

  • First1: This is the class name where the methods are defined.
  • object1: This is the name of the object we are creating in the Second2 class.
  • new: This is the keyword used to create a new object.
  • First1(): This is the constructor, which initializes the new object.

At the bottom of the image, there's the output of the code.
'Print of first Method'

Calling a Method:
object1.method1();

Here:

  • object1: This is the object we created earlier.
  • method1(): This is the method we are calling from the First1 class.

It’s important to note that method1 was defined in the First1 class.

Attaching an image of the first method from the class 'First1' for your reference.

Image description

Static Methods:
Static methods are special methods that can be called without creating an object. Since they are linked to the class, not to any instance of the class, we don’t need to create objects to use them.

I am attaching an image for your reference.

Image description

In this image, the marked part is the static method.

Image description

In this image, the marked part is the call to the static method. And at the bottom of the image you can see the code output.

Top comments (0)