Raghurocks
Raghurocks

Reputation: 925

Classes and its Objects

public class A
{
    private void sub()
    {
        add();
    }

    private void add()
    { 
          -----
    }
}

I can call the add method in sub like above and I can do the same as below

public class A
{
    private void sub()
    {
        A obj_A = new A();
        obj_A.add();
    }
    private void add()
    { 
           -----
    }
}

I would like to know the differences between them. Thank you.

Upvotes: 1

Views: 148

Answers (6)

Ajinkya
Ajinkya

Reputation: 22710

private void sub()
{
  add();
}

Calling method add() on the same object which called sub() method.

private void sub()
{
   A obj_A = new A();
   obj_A.add();
}

Creating new object of type A and calling add() method on it.

Upvotes: 0

Juvanis
Juvanis

Reputation: 25950

  • If you create an instance of A with the first class and invoke sub() you will have 1 instance of A within the method scope.
  • If you create an instance of A with the second class and invoke sub() you will have 2 instances of A wihin the method scope.

Upvotes: 4

Xetius
Xetius

Reputation: 46794

Java classes have a special member defined called this which refers to the current object.

This answer will give you more details on this.

Upvotes: 2

Averroes
Averroes

Reputation: 4228

In the first method you are calling the add method of the same instance of the class. In the second example you are creating a new instance of the class and calling its add method.

For example:

public class A
    {
        private int num = 3;

        private void sub()
        {
          num = 10;            
          add();
        }
        private void add()
        { 
              system.out.println(num);
        }
    }

public class A
{
    private int num = 3;

    private void sub()
    {
        A obj_A = new A();
        num = 10;      
        obj_A.add();
    }
    private void add()
    { 
           system.out.println(num);
    }
}

In the first example, it will print 10. In the second one, it will print 3. This os because in the first example you are printing num of the instance itself that you have previously modified. In the second example you also modify num value but since you are invoking add of the new class you have created it will print 3.

Upvotes: 1

NPKR
NPKR

Reputation: 5496

In second approch unneciserly we are creating Object.

First approch is better.

Upvotes: 0

Subin_Learner
Subin_Learner

Reputation: 377

By second method, to invoke add method two objects will be created, by using the method 1 we can access add method by just creating one object

Upvotes: 0

Related Questions