简体   繁体   中英

what is the best way to combine different JAVA classes in one single class?

I have 3 different JAVA classes named as A, B, C . All these classes contain either each other's reference object or a list of objects. My main aim is to combine all these classes into one single JAVA class (A). Please find below the structure:

public class A {

    private B b;
    ...

}

public class B {
    private List<C> c;
    ...

}

public class C{
    private TreeMap<int, int> t;
    ...
}

Since I am new to JAVA , I am not sure how would I combine these together into one single class 'A'? Experts please help me in this case.

Here's the class combined [single Java class (A)]:

public class A {
    private A b;
    private List<A> c;
    private TreeMap<Integer, Integer> t
    ...
}

Now, for a little OOP best practices rant. You need to think of each class as having a single responsibility ( single responsibility principle ). If you say, "this class does this and that". Then it has too many responsibilities. The key word is "and". It implies multiple responsibilities. If you can safely say, each one of these classes share a single responsibility, then I guess it's okay to join them together. However, I'm doubting this is the case. It seems to make more since to keep them split.

First of all, your code will not compile, we don't use TreeMap<int, int> , colections only use Objects, it's Javadocs :

A collection represents a group of objects, known as its elements.

Otherwise. your code seems to be good enough, regarding your comment:

simple exercises with JAVA collections and finding out the best practices for the same. This problem seems to be list of maps but I want to know whether that is the most optimized way of doing it or not?

your question has nothing to do with optimized use of collections, but if you are not willing to use class B and class C in other classes, then you can use inner classes like this:

class A {

   private B b;

   class B {
       private List<C> c;
       ....
    }
    class C {
       private TreeMap<Integer, Integer> t;
       ....
    }
}

More informations about how use inner classes, could be found here .

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