If any of those objects can be null, then you have to check for null before calling a getter on this object, of course.

But this kind of chaining is a bad smell of a lack of encapsulation (anemic objects having just data, and no behavior). You're violating the law of Demeter : don't talk to strangers.

Answer from JB Nizet on Stack Overflow
🌐
Aspose
forum.aspose.com › aspose.cells product family
How to use nested objects in java - Free Support Forum - aspose.com
June 24, 2014 - Hi, I am calling one class in another class. Here BasicDetails is my class which contains DerivedDetails class object. BasicDetails.java public class BasicDetails { private String accountID; private String accountName; public DerivedDetails derivedDetails; public DerivedDetails getDerivedDetails() { return derivedDetails; } public void setDerivedDetails(DerivedDetails derivedDetails) { this.derivedDetails = derivedDetails; } public String getAccountID() { return ...
Discussions

java - OOP Objects, nested objects, and DAO's - Software Engineering Stack Exchange
I've had this problem while working with PHP and Java so it's a fundamental understanding of OOP issue. Examples are in PHP. Let's say I have a few object's here. Song, Artist, ArtistProfile, User. So in some instances I want the ArtistProfile and an array of User objects (subscribers) when I call the Artist (e.g. the artist's profile page), in other instances I only want the Artist info, like when viewing a page of the song. Should I be nesting ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
What are nested objects in OOP concept? (mainly in java) - Stack Overflow
It was asked in an interview that what are nested objects ? give a real life example also. I end up saying that if we create an object of class B in class A and when the object of class A will be c... More on stackoverflow.com
🌐 stackoverflow.com
How to declare nested data object in java?
Your first example is using JSON text. You can search for "Java JSON" to learn about various libraries that parse JSON for use as Java objects. More on stackoverflow.com
🌐 stackoverflow.com
What is the best way to support nested object model in java? - Stack Overflow
I need to support UI client which has nested components. I have come up with below object model - public class SomeUserInterface { String name; List components;... More on stackoverflow.com
🌐 stackoverflow.com
November 6, 2016
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › nested.html
Nested Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used. As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's ...
🌐
WPI Computer Science
web.cs.wpi.edu › ~cs2102 › b16 › Lectures › types-and-nested-objs.html
Types and Nested Object References
So Java will not let you call canShelter on adultDillo. But wait – isn’t there a canShelter method sitting inside adultDillo? Yes, it is there, but Java won’t let you access it because of the type you ascribed. If you used type Dillo instead, you could call canShelter.
🌐
YouTube
youtube.com › watch
How to Create Nested Objects in Java Without Creating a Class - YouTube
Discover how to create nested objects in Java using maps instead of classes. Learn step-by-step to structure your data efficiently without the need for class...
Published: August 1, 2025
Views: 0
🌐
Example Code
example-code.com › java › json_nested_objects.asp
Java JSON: Nested Objects
String jsonStr = "{\"name\": \"donut\",\"image\":{\"fname\": \"donut.jpg\",\"w\": 200,\"h\": 200},\"thumbnail\":{\"fname\": \"donutThumb.jpg\",\"w\": 32,\"h\": 32}}"; success = json.Load(jsonStr); if (success == false) { System.out.println(json.lastErrorText()); return; } // Get the "image" object. CkJsonObject imageObj = new CkJsonObject(); json.ObjectOf2("image",imageObj); System.out.println("image: fname=" + imageObj.stringOf("fname") + ", width=" + imageObj.IntOf("w") + ", height=" + imageObj.IntOf("h")); // Get the "thumbnail" object.
🌐
DZone
dzone.com › data engineering › data › accessing nested data structures in java
Accessing Nested Data Structures in Java
March 27, 2021 - More often they are hierarchical, nesting one or more levels deep. For example, an account object might contain a customer object, which might contain an address object, and so on. Such data structures are often returned by web services. A single call to the server requires less code and incurs less network overhead than multiple calls to retrieve the same information. Often, these data structures are returned as JSON and mapped to strongly typed equivalents such as Java beans on the client side.
Find elsewhere
Top answer
1 of 2
3

Should I be nesting one object as part of another or should I be creating more specific objects for different usages.

  1. Follow OO principles first which means "more specific objects." In doing so your classes may "line up" with your database schema or not but do not let DB schema trump good OO design.

  2. Single Responsibility Principle will help guide you in what classes to build. SRP means, for example, that a Song is a song. It is not an artist, it is not a list of subscribers, so it should not have artist or subscriber stuff in it. Only song stuff.

  3. The above means that you will have lots of small, independent, fully functional things - classes. By "fully functional" I mean, if a Song is a name, date, and id then that's what's in it. period. The fact that a certain artist sings that song does not inherently, fundamentally define what a Song is. This means other classes to model relationships like "an artist's song repertoire" for example.

  4. Small functional classes leads to good DAO's and flexibility for your user interface.

Option 1 means wasting a lot of time/resources grabbing information I may not need for that page but easier to manage. Option 2 is messy and requires keeping track of which object is what but faster and far less db calls

  1. You are falling victim to premature optimization. How can you know up front that option 2 will have "fewer DB calls?" What does that mean anyway?

  2. This is simply the wrong way to think about your domain classes/model. This is why you end up duplicating your DB schema:

.

Class SongWithArtist {
  private $song; //Basic Song object
  private $artist; //Basic Artist object
}

When what you should have is something describing the real world:

Class ArtistPortfolio {
    private Artist $theArtist;
    private List<Song> $portfolio;  // list of songs (s)he sings 
}

Class ArtistSubscribers {
    private Artist $theArtist;
    private List<User> $subscribers;  // list of people who like this artist
}

// And it would probably make sense to combine the above 2 classes:

Class ArtistProfile {
    // an Artist object, not just an id. We're doing OBJECT oriented programming.
    private Artist $theArtist;

    private List<Song> $portfolio;  // list of Song objects 
    private List<User> $subscribers; // list of User objects
}

// and if you need a list of profiles...
Class ArtistProfiles {
    private List<ArtistProfile> $profiles; // a list of type ArtistProfile

    public ArtistProfile GetProfileByArtist (Artist thisArtist){}
    public ArtistProfile GetProfileByName (string name) {}
    public ArtistProfile GetProfileById (string id) {}
}

// I'd say a ArtistProfile could be part of an Artist..

Class Artist {
    private $id;
    private $name;
    private ArtistProfile $profile; // this is composition.
}


//In lieu of the above, an DAO oriented Artist composition ...
// Just go with the refactoring flow!
Class Profile {
    private $id;
    private $name;
    private $birthdate
}

 Class Repertoire {
    // a Profile object, not just an id. We're doing OBJECT oriented programming.
    private Profile $theArtist;

    private List<Song> $portfolio;  // list of Song objects 
    private List<User> $subscribers; // list of User objects
}

Class Artist {
    private Profile $me;
    private Repertoire $myStuff; 
}

Too Many DB Calls!

NOT. You can instantiate a Artist object without populating the $myStuff and in turn, defer populating $subscribers / portfolio lists until needed. This is called lazy loading.

2 of 2
1

I believe that what you want to do when programming in general is to avoid duplicating data.

When designing a relational database, there are 4 types of relationships:

  • one-to-one
  • one-to-many
  • many-to-one
  • many-to-many

For a many-to-many relationship, you have a "link table" in a database where usually just has the two IDs of the two records being linked to each other.

In addition to the two linked record IDs, a link table can have any other data associated between the two database tables with the many-to-many link table.

For example,

class DBRecord {
    private $recordID; // a BIGINT, auto-incrementing field, the primary key
}

class Product extends DBRecord {
    private $productID; // an ID that the user can set
    private $productName;
    private $suggestedRetail;
    ...
}

class Vendor extends DBRecord {
   private $vendorID; // an ID that the user can set
   private $vendorName;
   private $contactID;
   ...
}

class ProductVendors extends DBRecord {
   private $productRecordID; // this ID never changes
   private $vendorRecordID;  // this ID never changes
   private $wholesaleCost;   // the cost of a product can be different by vendor
}

In this example, objects of the classes: Product, Vendor, and ProductVenders are much like the records that are in the database. You could possibly read an entire database table into an array.

$products = readAll();
$vendors = readAll();
$productVendors = readAll();

Depending upon the size of your dataset in the number of records, you may not want to read them all into RAM.

When you have too many records to read them all into RAM, you can setup your relations between your objects to mirror the relations between your database tables in your relational database:

// database code is encapsulated in this class
class DB {
   ...
}

// this class implements functionality common to all subclasses
abstract class DBTable {
   private $db;
   private $internalName; // the SQL name for this database table
   private $displayName;  // the name that the user sees for this db table
   public lookup($productID) {
       ...
   }
}

class Products extends DBTable {
   ...
}

class Vendors extends DBTable {
    ...
}

class ProductVendors extends DBTable {
   ...
}

That's how I've done many-to-many relationships, and it works even for very large datasets such as maybe having 100,000 product record.

  • One-to-many and many-to-one are just the flip-side of each other

    class PurchaseOrderLineItem extends DBRecord {
    }
    
    class PurchaseOrder extends DBRecord {
        private $lineItems;
        public loadLineItems() {
           ...
        }
        public saveLineItems() {
           ...
        }
    }
    

A line-item of a purchase order can only be on one purchase order document, but a purchase order document can have many line items on it. This generally isn't a huge number of line-items, so I just load them all into RAM, into an array.

  • One-to-one relationships

    class Product extends DBRecord {
        private $itemRecordID;
        private $inventoryOnHand;
        ...
    }
    
    class InventoryCount extends DBRecord {
        private $itemRecordID;
        private $inventoryCounted;
    }
    

These two records are a one-to-one relationship. When counting all of the inventory in a store, for each product there is only one count, and for each count, there is only one product.

So, those are the four types of relationships. I think that the most general solution is to mirror your relational database, but I don't always do that such as in the case of purchase orders which "contain" their line-items.

Watch out for multi-user problems The famous lost-update problem.

Don't duplicate data See "Normal forms".

Store date-of-birth -- not age Generally it's best to not store an age, but a date-of-birth and have an accessor called "getAge()" to calculate and return an age.

🌐
CopyProgramming
copyprogramming.com › howto › how-to-create-nested-object-in-java
How to Create Nested Objects in Java: 2026 Complete Guide with Latest Features & Best Practices - Complete guide with latest features
December 28, 2025 - Creating nested objects in Java is a fundamental technique for building well-organized, scalable applications. Nested objects—also called nested classes—are classes defined within the body of another class, enabling developers to logically group related classes and improve code maintainability.
🌐
W3Schools
w3schools.com › java › java_inner_classes.asp
Java Inner Class (Nested Class)
Nest a class inside another class in Java to group related types together.
🌐
CodingTechRoom
codingtechroom.com › question › -nested-arrays-in-java
How to Work with Nested Arrays in Java - CodingTechRoom
Solution: Ensure your nested array is properly initialized before accessing its elements. ... A broad desk reference for the Java language and standard library.
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-parse-a-nested-json-object-in-java
How can we parse a nested JSON object in Java?
April 22, 2025 - Now, let's see how to parse a nested JSON object using the Gson library. Gson is developed by Google to help Java developers to work with JSON data. Let's see how to use it. In order to use this library, we need to add the Gson library. We can either download it from its official website or include it in our project if we are using Maven or Gradle.
Top answer
1 of 1
2

It's somewhat easy if all of your fruit implement a common interface. It's a lot more difficult if they don't, to the point where I'd probably suggest using another language altogether. Java's not suited for that.

If they implement a common interface, you can use Class.forName to get the class, and then getConstructor to be able to instantiate the objects:

Basic interface (yours would probably declare more useful behaviour) :

public interface Fruit {
    String getName();
}

Apple:

public class Apple implements Fruit {
    private final Fruit child;

    public Apple(final Fruit child) { this.child = child; }

    @Override
    public String getName() {
        return "I am an apple " + (child == null ? "" : child.getName());
    }
}

Banana can be basically identical to Apple, just with a different name.

Strawberry:

public class Strawberry implements Fruit {
    @Override
    public String getName() {
        return "I am a strawberry";
    }
}

Main method is below. We need to iterate in reverse through the array in order to build the child objects first.

@SuppressWarnings("unchecked")
public static void main(final String... args) throws Exception
{
    String[] splitted = {"Apple", "Banana", "Strawberry"};
    Fruit prevFruit = null;
    for (int i = splitted.length - 1; i >= 0; --i)
    {
        final String className = splitted[i];
        final Class<? extends Fruit> clazz = (Class<? extends Fruit>) Class.forName("my.pckage." + className);
        if (prevFruit == null) // if first, use no-arg constructor
        {
            prevFruit = clazz.getConstructor().newInstance();
        }
        else
        {
            prevFruit = clazz.getConstructor(Fruit.class).newInstance(prevFruit);
        }
    }
    System.out.println(prevFruit.getName());
}

Sample output:

I am an apple I am a banana I am a strawberry

🌐
Baeldung
baeldung.com › home › json › jackson › mapping nested values with jackson
Mapping Nested Values with Jackson | Baeldung
January 8, 2024 - To map the nested brandName property, we first need to unpack the nested brand object to a Map and extract the name property. To map ownerName, we unpack the nested owner object to a Map and extract its name property. We can instruct Jackson to unpack the nested property by using a combination of @JsonProperty and some custom logic that we add to our Product class:
Top answer
1 of 1
1

Collections can be initialized at definition point

public class RootNode {
    public Set<ShiftDate> shiftDateSet = new HashSet<>();
}

public class ShiftDate {
    public LocalDate date;
    public Set<Location> location = new HashSet<>();
}

public class Location {
    public Set<ShiftType> shifts = new HashSet<>();
}

This way when calling the RootNode constructor

RootNode rootNode = new RootNode();

It will initialize every nested object initializing its sets with empty HashSets Also... empty constructors are already defined if no other constructor is going to be declared, so it's redundant

EDIT:

To initialize anything more than just an empty set use the constructor

public class Location {
    public Set<ShiftTypes> shifts = new HashSet<>();
    public Location() {
        shifts.add(ShiftTypes.MORNING);
        shifts.add(ShiftTypes.AFTERNOON);
        shifts.add(ShiftTypes.NIGHT);
    }
}

This time I assumed you wanted the set in Location to be of type ShiftTypes and not ShiftType, otherwise you can't fill it with every enum type because ShiftType itself is not an enum

If ShiftType should be used (because you need the integer) then that's a whole different story you'll have to add a field in ShiftType

public class ShiftType {
    public enum ShiftTypes {
        MORNING, AFTERNOON, NIGHT
    }
    public ShiftTypes shiftTypeEnum;
    public Integer count;
    
    public ShiftType(ShiftTypes shiftTypeEnum, Integer count) {
       this.shiftTypeEnum = shiftTypeEnum;
       this.count = count;
    }
}

And the above method becomes

public class Location {
    public Set<ShiftType> shifts = new HashSet<>();
    public Location() {
        shifts.add(new ShiftType(ShiftTypes.MORNING, 0));
        shifts.add(new ShiftType(ShiftTypes.AFTERNOON, 0));
        shifts.add(new ShiftType(ShiftTypes.NIGHT, 0));
    }
}