heartisan
heartisan

Reputation: 13

How many copies of a method are generated when multiple instances of a class are made?

For example, I generate a class like this:

public class Test {
  public void sayHello (String name) {
    System.out.println("Hello, " + name);
  }
}

When I create multiple instances like this:

Test t1 = new Test();
Test t2 = new Test();

So do the objects t1 and t2 share the same method sayHello, or they just all have their own sayHello method?

Upvotes: 1

Views: 675

Answers (3)

xsami
xsami

Reputation: 1330

They have each one their own sayHello method. And the best way to prove it is with a example like this:

public class Person {
    
    private String name;
    private int age;

    public Person ( String name, int age ) {
        
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return "Hello " + name + ", you have " + age + " years!";
    }
}

And you have another class with this:

class Myclass {
    public static void main ( String [] args ) {

        Person object1 = new Person( 'Edward', 19 );
        Person object2 = new Person( 'Fredd', 21 );

        System.out.println(object1);
        System.out.println(object1);
    }
}

The output are:

Hello Edward, you have 19 years!

Hello Fred, you have 21 years!

This means that each object no depends on the other.

Upvotes: 2

tonychow0929
tonychow0929

Reputation: 466

In practical case, if you want to share the same method sayHello, you can declare it as a static method.

public static void sayHello (String name) {
    System.out.println("Hello, " + name);
}

Then Test.sayHello() (recommended), t1.sayHello() and t2.sayHello() will have the same effect.

Otherwise if sayHello is an instance method (i.e. normal method without the static keyword). You can use the keyword this to refer to the instance.

For example,

public void sayHello (String name) {
    System.out.println("Hello, " + name);
    System.out.println(this);
}

You will observe the difference if you call t1.sayHello() and t2.sayHello() respectively.

So back to your case, if your instance method does not include the use of this, you should consider declaring it as static (so that you don't have to create a Test object before calling it).

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Methods belong to all objects of a class, no matter how many objects you instantiate. The code for all methods of a class is placed in a shared place in memory, and all instances of the class reference the same code for each method.

Such sharing is possible because method code does not change from instance to instance.

Upvotes: 2

Related Questions