Object #
An object groups data in a meaningful way.
A simple example: JSON #
Here is a JSON object (in Javascript syntax) that describes the city of Florence:
{
name: "Florence",
zipCode: 50100
}
A JSON object may contain other objects, as well as arrays (of values, objects or arrays). For instance:
{
name: "Alice",
age: 26,
birthPlace: {
name: "Florence",
zipCode: 50100
},
jobs: [
{
employer: "Kolping",
start: 2021,
end: 2022
},
{
employer : "Eurac",
start: 2023
}
]
}
In JSON:
- an element can be either:
- a scalar (e.g. an integer), or
- an array of elements, or
- an object,
- an object is a finite set of key-value pairs, where keys are distinct, and each value is an element.
Besides, a JSON element must have finite depth.
Equivalently, a JSON object can be viewed as a function (with finite domain) that maps keys to JSON elements.
Objects and programming languages #
JSON objects do not exactly correspond to the objects that can be created in Java (and many other programming languages). We highlight here two important differences.
Types #
In a statically typed language (like Java), the elements of an array must be of the same type (whereas this is not required in most dynamically typed languages like Javascript, Python, etc.)
Example. This is a valid JSON object. It has no immediate equivalent in Java.
{ key: [1, [2, 3]]; }
References #
A Java (or Python, C#, etc.) object does not contain objects or arrays, but references to objects or arrays.
Example. The Java object below (abusing notation) is the analogous of the JSON object above:
#1: { name: #2, age: 26, birthPlace: #3, jobs: #4, } #2: ['A','l','i','c','e'] #3: { name: #5, zipCode: 50100 } #4: [ #6, #7 ] #5: ['F','l','o','r','e','n','c','e'] #6: { employer: #8, start: 2021, end: 2022 } #7: { employer: #9, start: 2023 } #8: ['K','o','l','p','i','n','g'] #9: ['E','u','r','a','c']
Each object or array has an ID (e.g. #1 in this example), which can be used to refer to it (we can think of this ID as an address in memory).
Consequence. Some objects can be created in Java that have no (finite) representation in JSON.
Find one of these objects.
#1: {
name: #2,
friends: #3
}
#2: ['A','l','i','c','e']
#3: [ #4, #7 ]
#4: {
name: #5,
friends: #6
}
#5: ['B','o','b']
#6: [ #1, #8 ]
If we try to represent these objects in JSON, we get (assuming that we start with Alice):
{ name: "Alice",
friends: [
{ name: "Bob",
friends: [
{ name: "Alice",
friends: [
...
]}]}]}
Hint. Cyclic references (like in this exercise) naturally occur in object-oriented code. Identifying them may be essential to debug a program that does not terminate or runs out of memory (stack overflow, …).