简体   繁体   中英

How to avoid to Reference a Java object multiple times

In some way I'm trying to avoid multiple reference to an specific object. I have the following:

public class A
{
   private C c;
  
   public A()
   {
      this.c = new C();
   }

   public C getC()
   {
       return this.c;
   }
}

Then I have:

public class B extends A
{
   private C c;

   public B()
   {
       super();
   }

   public void someMethod()
   {
       // I want to avoid this
       this.c = getC();
     
       // But I want to allow the execution of methods inside C
       getC().someMethodOfC();
   }
}

I guess that in C++ it could be done with some operator overloading but I've seen that in Java this is not possible.

Is there any way to only have one reference of the object in Java (And don't allow the creation of more references)

I don't think I understand your question fully. You may make C a private inner class in A, expose a method in A that uses C to perform the operations/actions that you want.

Remove private C c; in class B . By extending B from A , you have access on public and protected members of A . This includes public C getC() of class A . If you want direct access on member c of A in B , make c protected .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM