Collin Dutter
Collin Dutter

Reputation: 47

What is the advantage to declaring objects in fields?

How is typing:

public class Example  
{  
    private Cat whiskers;  

    public void makeCat()  
    {  
        whiskers = new Cat();  
    }  
}  

different than:

public class Example  
{  
    public void makeCat()  
    {  
        Cat whiskers = new Cat();  
    }  
}

it seems that the first example is more work because you can now only create Cat objects named whiskers from it. Why declare it at all?

Upvotes: 0

Views: 86

Answers (4)

Jatin Khurana
Jatin Khurana

Reputation: 1175

An Object is declared in the field of the another object when first object is the part of the second object. Example-:

class Product
  {
    int productId;
    ProductDetail detail;
  }

class ProductDetail
   {
     string brand;
     int price;
     string description;
   }

In the above example, one object of product class corresponds to the one Product and each product has some details.So whenever Product class object is created ProductDetail class object is created by the JVM.

In case of your first scenario, When Example class object is created anywhere then Cat class object is created by the JVM. In case of second scenario, It is just a local variable in that method. And there is no Cat Object while creating the Example class object.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425003

The difference is that the first example uses a field (a.k.a. "instance variable "), which other methods can also reference (ie "use") it without it being passed to the method.

The second example is a local variable - it can only be used within that method (or other methods if passed to them).

Upvotes: 0

Ulises
Ulises

Reputation: 13419

In the first you are declaring a private variable that may be used within the same instance by other methods (or properties). However, in your second example you are just declaring a variable with a local scope, in other words, this variable will only be visible within makeCat().

Upvotes: 2

Karthik T
Karthik T

Reputation: 31952

It looks like you need a good book about the basics of Object Oriented Programming.

In the first case you are declaring a "private member variable". This is now a part of the class and can be used in other member functions or even from outside.

In the second case you are declaring a "local variable". This is a variable that is valid only within the function in which it is defined, and it is used for calculations within the function only. It cannot be accessed from outside/from other functions of the class.

Upvotes: 1

Related Questions