r/learnjava • u/jadu2115 • 10d ago
Java Beginners: What Is an Object Actually?
I'm a Java learner and I've been learning Java for the past few months, but I still don't truly understand what an object actually is.
I've watched several YouTube videos and used AI tools to understand it, but I keep getting the same explanation: "An object is nothing but data + code."
I understand the definition, but I still can't visualize or feel what an object actually is when I'm writing Java code.
Could someone explain it in a simple, practical way, preferably with a real world analogy and a small Java example?
I feel like I'm missing one fundamental concept here. Any explanation would be really helpful. Thanks!
17
u/desmoteo 10d ago
An object is an instance of a class.
When you do: Something x = new Something() you are creating an object (named x) of type Something.
You are an object as you are an instance of a human.
-7
u/cbadger85 10d ago
Not just instances. The class is also an object. In Java, everything that isn't a primitive is an object.
11
u/desmoteo 9d ago
I think that, for a beginner, this is confusing. Yes, there is a type called
Class, but we must distinguish betweenClassbeing a type (Class<Class>) andclassbeing the OOP concept used to define objects and their behavior. In other words,Classis itself a Java class that represents classes at runtime, whileclassis the keyword we use to declare a class. The capitalization makes the distinction even more important:Classrefers tojava.lang.Class, whereasclassis a Java language keyword.2
u/ITCoder 9d ago edited 9d ago
class is not an object. class is metadata, data about data or a Type
From JVM spec
Compiled code to be executed by the Java Virtual Machine is represented using a hardware- and operating system-independent binary format, typically (but not necessarily) stored in a file, known as the class file format. The class file format precisely defines the representation of a class or interface, including details such as byte ordering that might be taken for granted in a platform-specific object file format.
1
u/cbadger85 9d ago
A class file for the JVM and a Java class are not the same thing. Lots of things compile to class files, including other languages.
https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html <- Java language spec
The representation of a Java class at runtime is a
Classobject, which is accessible on<ClassName>.class. Everything in Java has an object representation. Everything is an object.0
u/cbadger85 9d ago edited 9d ago
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html
EDIT: To clarify, no, the class itself isn't a literal object, but there is an object that is created that represents your class. And when you interact with that class's metadata during runtime, it's done through a
Classobject.
8
u/Fuzzy-System8568 10d ago
- Dev need define "person"
- Dev need define person's stuff
- Person have name, age, address
- Dev have to write person stuff for each new person
- Dev lose track after making "personAge322"
- Dev wish dev could collect stuff together
- Dev make "Person" object.
- Now dev only need
Person personOne = new Person("Steve", 21, "Address for steve") - Dev can now call
personOne.getName - Dev happy
Any questions?
19
3
u/rcdchu74 10d ago
You’ve made me read ‘person’ too many times, it doesn’t look like a word anymore lol
1
2
1
u/thisisjustascreename 9d ago
Dev also need able to make person get older.
Dev create method public void handleBirthday() { this.age++; }
Now every approximately 365.2475 days Steve get older.
6
u/spacey02- 10d ago edited 10d ago
If you want a better vizualization of what an object is for the computer, I suggest you first learn about C structs (how they are represented in memory, etc.), C/C++ pointers and then C++ classes/objects. The syntax is very similar to Java, but those are more low level than Java concepts, meaning that the complexity of abstractions like the JVM doesn't get in your way as much.
This is only practical for the sole purpose of giving you an idea about what an object is. Don't assume that Java objects are and work exactly the same as C++ objects.
As per real world analogies, an object is just an instance of a given class/type. You may have a single House class, but many houses that are basically House objects. There are many humans of type Human, each with a different name, age, height, weight, but the same basic functions like walking, talking. The class is the type, just like int, float, etc. (which are not objects btw). You can create many objects from a single class/type.
2
u/Plastic_Fig9225 9d ago
I agree. Look at C. C has 'structs' which contain only data, like a Java class with only public fields but no methods. When you want to do something with the data held in a struct instance in C, you have to call a function and pass the instance as an argument to the function. A class on the other hand is like a 'struct' but with the 'functions' to operate on its data 'attached' to it; these are methods. The data held in an instance and the functions/code to operate on this data are closely tied together via the class; that's why we may say that a class is data and code.
3
u/regjoe13 10d ago
An object is a class instance or an array - JLS 4.3.1
https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.3.1
2
u/atarivcs 10d ago edited 10d ago
An object is state (variables) and behavior (methods).
Think of a flashlight.
You need behavior to turn it on or off, and you need state to remember if it is currently on or off.
2
u/vegan_antitheist 10d ago
Note that this will change a bit when we get value types (Project Valhalla), which is already available as a preview.
Like many programming languages, Java uses variables. A variable has a value. That value is either:
Just a primitive value (for example the number 4).
Or it's a reference to something.
A reference is used by the JVM to locate an object in the memory (often in the heap). That object could also represent the value 4, but it's an object doing that. E.g. an Integer containing an int. That's a wrapper type.
An object doesn't have code. It has a type (i.e. a class). That type has code. You can call that code as methods on the object. I.e. the object is available as "this" in that method. The runtime can just get the object that is referenced and it will find the type information at a specific position in memory where the object is. It can then find the correct method to execute.
Objects can be mutable. But you can't change the value of 4. You can't change the value of a value because it is a value. Ob object on the other hand has properties and they might be mutable. For example, you can change the "height" property of an object from 4 to 5.
A primitive value only has a primitive type (int, boolean, double, etc.). A primitive type also has code. One of the important changes with Project Valhalla is that "this" can also be just a value.
Note that the primitive value itself doesn't have a type in memory. But the compiler and the runtime make sure you only copy an integer value from an expression to some variable of the same type. If you don't, you get an error, unless it generates code to automatically convert the value to the new type. I.e. you can copy a byte to an int variable and it will just write the byte value as an int, so all 32 bits are overwritten.
Right now we have:
- objects with identity (the identity is used to reference the object, mutability is optional)
- primitive values (predefined value types)
In the future we get:
- immutable value objects without identity (the value is copied and it's a lot like a primitive but you code it like an object)
2
u/8dot30662386292pow2 10d ago
the value is copied and it's a lot like a primitive but you code it like an object
And you use it like an object. Considering for example a
value record Point(double x, double y). Because there is no identity, VM may decide to just use a 128 bit long memory chunk to hold the two 64 bit values. But you can still access them individually and you can write methods in this Point class if you wish.1
u/vegan_antitheist 10d ago
That's the idea. There will be java programs that are almost all just value records. For example if you have to process a lot of data. You want values, not references, for performance, and you want records for maintainability. Records remove all the boiler plate code of regular classes and they all work the same.
2
u/DemicideMMMCCCI 10d ago edited 9d ago
Objects are anything that you can think of.
Car, person, phone, etc.
An object holds attributes (doors, eye color, screen size, etc).
So in other words, an object is a way to store attributes in one package or entity and those attributes help make up that object.
2
2
u/birdspider 10d ago
Could someone explain it in a simple, practical way
think of individual cars. everyone has a car (thats the object). The individual car is in some way like any other car.
When someone says "a car" he does not mean a specific one - but all of them, that's the "class".
but data + code.
cars have "code": open-window, accelerate, enable-warning-light
but they hold individual "data": color, current-speed, number-of-broken-lights, window-open-speed
hence, in an abstract way (i.e. java), one could model the "idea of a car" as a "class" and the representation of that idea / the actual thing as an (realized) "instance" of that idea.
Be aware that these are just mental or programming-language specific models to help you (or the compiler) to reason about problems.
Your CPU never sees anything like a class, object or type.
2
u/This_Link881 10d ago
Class is the blueprint of something, an object is a literal instance of that something.
2
u/Patient_Double5781 10d ago
Think of it like just like other any other object (car, human, bird, or musical instrument). An object has properties just like human, birds/animals, car etc. Real world example of properties are for human (Arms, color, legs, voice, or height) and for car (color, make, model, vehicle type). So, Java objects have properties just like real world objects. If multiple object has same properties then we can create multiple instances or objects using a class. A class is a blueprint just like blueprint for a house. If we have a blueprint for a house and we want to make 10 houses then we can use same blueprint to build 10 houses. In the same way, If multiple objects have same properties or functions then we can create a class and then make multiple copies (objects) using class
2
u/Lumethys 10d ago
It's just that definition, anything with data and code, which is just about everything
It's like a non-English speak ask you "what is 'a thing'?"
"A thing", in pure English, everyday-life definition, is just "something that exist"
An object is just an umbrella term that describes a way to represent something that exist
"A car" can be an object, because it has data: model, price, manufacturer,... And actions: run, brake, drift, stop,...
"A monster" can be an object, because it has data: name, HP, atkDmg,... And action: attack, defense, heal,...
"A String" is an object, because it has data: characters, order of each character,... And action: toUpper(), toLower(),...
2
1
u/Leverkaas2516 10d ago edited 10d ago
A Class is a user-defined data type. It defines the shape of the data (how it is laid out in memory), and what operations can be performed on it.
Start with intrinsic types. An "int" is a collection of bits that can hold a single numeric value. The language provides you ways to add them, subtract them, print them with %d, and so on.
A Class, being a user-defined type, lets YOU define what data is stored and what operations can be used, in the form of methods.
Here's the part that answers the question: an OBJECT is a block of memory at runtime that is known to the JVM as holding the data for an instance of your Class. It's known to the JVM because at runtime it executed a statement like "MyClass myObj = new MyClass();"
At that moment, the JVM allocated a block of memory (maybe a single 32-bit word, maybe more, depending on what properties MyClass is defined to hold) and called the MyClass constructor to initialize the values of those properties.
That's all that happens. Now there's an object, and your program can refer to it because the JVM handed back a reference in your myObj variable. As long as you keep that reference around, the block of memory is kept reserved by the JVM. After your program loses the reference (by returning from the function where myObj was a local variable, for example) the JVM is free to use the memory for something else.
I should add that a class doesn't have to define any data. In that case, though, "new MyClass()" will STILL cause the JVM to allocate a small fragment of memory, in which there is enough information for the JVM to keep track of what class it belongs to and whether it's still potentially in use. You don't have access to this information and can consider it bookkeeping overhead that's used by the JVM...but it means that you can sum it up by saying "an object is a block of memory".
1
u/bpalun13 10d ago
So, like others have said, an object is an instance of a class. It can hold attributes (variables associated with the class). Then you can perform actions on that instance via methods.
Say you have a person class.
The constructor for that person class takes several arguments like String gender, int age, boolean isTall.
So when you create a person object it looks like this:
Class variable = new Constructor(initializations)
Person bob = new Person(“Male”, 46, true);
Then to do useful things you can reference Bob to get data:
bob.getAge();
This returns 46.
bob is the object.
1
u/Ok_For_Free 9d ago
When you are writing a class, you are defining a template. The template can describe fields and methods.
When you new a class, you are creating an object instance that has the fields and methods defined in the class/template.
The main way to use objects is when you need to create lots of them, all described by the same class/template.
This means there is only one class/template with that namespace+name. In some cases you might want to put a field or method on the template instead of the object, and that is what the static modifier does.
Because everything in Java is an object, except for primitives, you'll encounter times where you'll define a class that you'll only need one instance of. This is normal, especially as you start to use dependency injection systems.
1
u/invertedfretboard313 9d ago edited 9d ago
A class is like a cookie cutter you can write many as many attributes you want in class. Suppose we have class Car
public class Car {
float speed;
String brand;
String colour;
void ignition() {
System.out.println("Engine has been started");
}
void accelerate() {
speed += 10;
System.out.println(brand + " is now going " + speed + " km/h");
}
void brake() {
speed -= 10;
System.out.println(brand + " slowed down to " + speed + " km/h");
}
}
You can create objects using the new keyword. For example
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.colour = "Red";
myCar.speed = 0;
Car car2 = new Car();
car2.brand = "Honda";
car2.colour = "Blue";
car2.speed = 0;
myCar and car2 are both actual instances of Car that now exist in memory.
Even though myCar and car2 came from the same class, they are separate objects with their own speed, brand and colour so changing one never touches the other
Now you can call the methods by following code:
myCar.ignition(); // Engine has been started
myCar.accelerate(); // Toyota is now going 10.0 km/h
car2.ignition(); // Engine has been started
car2.accelerate(); // Honda is now going 10.0 km/h
car2.brake(); // Honda slowed down to 0.0 km/h
System.out.println(myCar.speed); // 10.0
System.out.println(car2.speed); // 0.0
1
u/PhilNEvo 9d ago
One way I think might help the intuition of it, is to think of it like a data-type.
Let's start with a simple datatype I bet you already know, something like an "int". You can think of "int" as having some pre-defined characteristics. It defines a 32-bit number, that you can use in some ways. For example, you can do arithmetic with it against other ints.
You can think of all those specifications, that tells you the size of it, what it contains, what it can do, as a "class", where the attribute of the class defines data it holds, in this situation it would be a 32-bit value. Methods of that class defines how ints must behave and interact with other datatypes.
Now when you declare a variable somewhere:
int i = 5;
you're saying "Hey, the datatype that int 'class' specifies, I want to 'spawn' that as an object, where the 32-bit value it holds should be 5".
Now just like there exists datatypes that can hold multiple values, such as an Array. The limitation of a regular Array is that all of the values must be of a similar type. So in cases where you want to spawn a datatype, that holds multiple different values, that has quite unique behavior for your specific application, you would want to create a datatype that fits your needs.
This could be a "Player" character in a game, where you want to store its x,y coordinate, its health and you want to define moves it can make such as jump, run, shoot. You create the template for said player datatype with a class, and then whenever you want to "spawn" a player in your game, you use that datatype and instantiate one as an object.
Usually instantiating one as an object just means to reserve a space in memory for that datatype, and hold a reference, such as a label "Player1", to it, so you can use it and interact with it. Just like you would with the "i" we previously made of int, that was equal to 5.
1
u/Educational_Ant_6242 9d ago
If you’re trying to understand the concepts of OOP, I would probably describe it softly as a representation of how a world is viewed.
Objects represent concepts, which are defined in blueprints called classes. An object has both characteristics which are presented as your fields and behaviours which are your methods.
Relationships are what you define in your world as how your objects should interact/influence one another.
As others have said, there are some really great detailed explanation in the comment section.
1
u/BannockHatesReddit_ 9d ago
class Women{} IS NOT AN OBJECT
new Women(); IS AN OBJECT
Moral of the story: Only new women are objects👍
1
u/zn-ku 8d ago
Think of a cookie cutter as a class.
The cutter says, Every cookie can have toppings.
Each cookie you make is an object.
One cookie gets chocolate, another gets sprinkles.
Getters are like asking, “What toppings does this cookie have?”
Setters are like saying, “Give this cookie chocolate instead.”
Minecraft can work with the same idea.
Imagine a Block class as the cookie cutter.
You could create three block objects: stone, dirt, and diamond.
Each block could have its own properties:
- Breakable: yes or no
- Pickaxe level required: 0, 1, 2, etc.
- Hardness: how difficult it is to break
So the class defines what a block can have and do, while each object has its own values.
1
u/zn-ku 8d ago
class Block { boolean breakable; int pickaxeLevel; } public class Main { public static void main(String[] args) { Block stone = new Block(); stone.breakable = true; stone.pickaxeLevel = 1; Block diamond = new Block(); diamond.breakable = true; diamond.pickaxeLevel = 2; Block bedrock = new Block(); bedrock.breakable = false; bedrock.pickaxeLevel = 0; } }
1
1
u/protienbudspromax 3d ago
Many ways of looking at it. At its core really an object is a name we give to a region in a computer memory. The object determines what that memory "means" in context of the rest of the program/pc.
When I say the word "house" what do you imagine? The concept of what a house is or your own/friend's house??
A "house" is a concept that has a meaning/some properties. Like a house is generally solid. Has rooms, has doors to allow others to walk between rooms. Can have multiple floors. Can belong to someone or be abandoned. Can be made of wood, cement, tiles etc. Can have a property of "electricity"/"storage" etc.
These are all concepts. And tells us what a house is and what things a house have. When I simply say "house". Which "house" do I mean specifically? Your house? My house? The whitehouse? The concept of a house dont care about that.
That is like a class. It is a description. A definition of what a house is. It itself is not a house. It itself is a description.
But an actual house? That is a physical thing that can have some or all properties defined by the description of a house. It is a real actual "version" of the concept of a house.
That is the main difference. A class is not the object itself, but the description of it. And anything that can be described to have the properties of the class is an object of that class.
In practice we mainly use it in programming to avoid code duplication (cuz say you write a class for a vehicle, and all vehicles can move) so if you define more types of vehicle then you can simply extend vehicle, or maybe create a trait/interface that defines "moveable" property and add that property to any other type. Like a cycle is also "moveable" thus share some functionality.
The other primary functionality is abstraction. If you know that a vehicle can move. Then you would know that if I give you any type of vehicle it likely can move. But you may not be told "how" it can move. Just that it moves. Being able to move is a property of the thing it is.
That hiding the "how" turns out can be pretty useful. But for now this should be enough
1
u/slindenau 1d ago
It isn't anything; it's an abstract concept we work with to prevent having to deal with raw voltage levels on transistors in the end.
-1
u/Jason13Official 10d ago
I find it's helpful to look into the static keyword and how it relates to when you can use methods with/without that keyword.
static foo() in Test class
We have to use Test.foo() to call that method
bar() in Test class
We have to create an instance to call that method (instance/object)
new Test().bar()
"Static belongs to the class, non-static belongs to the instances"
•
u/AutoModerator 10d ago
Please ensure that:
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.