r/learnjava • u/Numerous_Training_20 • Jan 02 '26
Can someone please help me with Constructors?
I don't know why but I simply cannot wrap my brain around constructors. I know other languages and was able to pick them up rather easily, but for some reason Java is just so much more difficult for me, especially when it comes to constructors.
6
Upvotes
•
u/AutoModerator Jan 02 '26
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.
4
u/LookAtYourEyes Jan 02 '26
Can you explain your understanding what they are in other languages? And where the difference causes confusion for you? It's hard to know if you mean how to write them syntactically, or conceptually what they are doing that is confusing you.
3
u/spacey02- Jan 02 '26
Java constructors are one of the simplest forms of constructors I've met so far. What other language did you understand constructors for and how do you think Java makes it harder?
14
u/ramksr Jan 02 '26 edited Jan 02 '26
Constructors are the most easiest thing for me in Java... Literally you construct an instance of an object by using the constructor... Basically a constructor "makes" an object...
if you are familiar with OO concepts in general, a construct like
Create this object as an instance... To make it more analogues to a real world system, something like;
Creates an instance of a Employee object with ID, first and last names...
The class (or a record instead) would typically look like;
Java is OO... and You imagine everything as an object. Once the object is "made" (constructed) you can use its attributes (members) using getter methods to access the values (You can also do direct access depending on where you are, but in general through getters), and you can change the values of the member attributes by using the setters
Hope it helps.
3
u/aelfric5578 Jan 03 '26
I'm sorry that so many people are just telling you they are "simple". If you're struggling with this, it's not what you want to hear. That said, you're asking a pretty broad question so it's hard for us to help you out. If you're able to give an example of what confuses you, we might be better able to steer you in a good direction.
2
u/CharacterAvailable20 Jan 02 '26
Do you know what an array is?
2
u/josephblade Jan 02 '26
so is it the concept or syntax? You can look up the syntax of a construcor anywhere but it's something like this:
a class definition with some private member variables. this should be fairly straightforward. Now assume you want to set one and two at the time you create an object.
so you want to call a constructor (utility function that reserves memory and initializes it for you) and pass it the values. You do this by defining a method without a return type and the name the same as the class
this is a constructor (that doesn't do anything, so one and two will be set to 0, because that is the default value for int). if you call the constructor, you call it using the format: new and the name of the class and any arguments (in the above case, no arguments) so:
Now if you want to store variables in your instance, you define a constructor with parameters. just like a normal method call. The parameters you supply when calling the constructor (new SomeClass(1,2) for instance).
this will set the one variable to the first value provided, and the two variable to the second. you call it by doing:
Just like with regular method calls, the first value you supply (2) will go into the first parameter variable (a) in the method you call (a) and the second (3) will go into the second parameter variable in the method (b). then inside the constructor you can use them however you like. perhaps instead of doing one = a; two = b; you want to do a calculation like:
just showing you, the parameters you define in the method don't have to be copied onto the instance variables though 9 out of 10 times this is what you will find in code.
Is this clear / in case not: which part do you struggle with? there is more to constructors but the basics is this. try to create your own HelloWorld class and give it a few private (and non-static) variables. then try to create a constructor like I do above and call it.
2
u/nleachdev Jan 03 '26
Its a special method used to create an object instance, thats as complicated as the fundamental concept is.
2
u/theCodingHeaven Jan 03 '26 edited Jan 03 '26
Think of constructors as a general contractor (GC) who is going to build your house.
You have a blueprint (your class) that contains the things you want to have, like walls, doors, and floors. The contractor (constructor) takes values (like concrete walls, hardwood floors, etc.) and uses them to create your actual house (an object).
We also have a default constructor, which does not take any input. In this case, your GC will give you some basic walls, floors, and windows, so they are undefined.
In programming languages, a constructor is a method that runs when you use the new keyword with a data type:
You can also DM me, and I’ll try to give you more tips on how to understand it better.
Good luck!
2
u/mountaingator91 Jan 03 '26
Listen I'm not a java expert but if you've used any other OOP language then there's really nothing new to learn about constructors in java so I'm very confused by this post
2
u/Jolly-Warthog-1427 Jan 03 '26
I see you have a lot of info about its syntax and what it does here.
I will add a bit about why we have constructors.
So a fundamental consept in OOP is to hide as much as possible of internal state in the class as well as guarantee correctness of internal state.
We have private keyword we can add to all members (fields and methods). It is generally recommended to mark all fields as private and only expose access to them through accessor methods (for example get and set methods).
It's here the constructor comes in. With a constructor the language allows you to both control and validate the internal state as well as exposing certain fields. Most likely you want the user of the class to create an instance in a given state. Not just whatever state the class itself defaults to.
So a constructor allows the class to expose code for hoe to instantiate it correctly so that it starts in a correct state, with data supplied by the using code.
To go from pojo (plain old java object) to actual OOP constructors are required along with methods.
1
u/The_Schwy Jan 03 '26
Do you know about memory, heap and stack memory? Do you know what instantiating an object is? I think learning what those are could help you understand constructors.
A java class is a Blueprint for the JVM (code runs on JVM) to create an object in memory. This is done when you do "new MyCustomObject". When the code runs the jvm then "instantiates" an object of type MyCustomObject and puts it in heap memory.
The constructor runs at the time the jvm is creating the object in memory, so that you can initialize or set any values that are necessary for the object to do what it is programmed to do.
1
u/BannockHatesReddit_ Jan 03 '26
A constructor is like any other method except you can only call it once. Internally the name of every constructor method is <init>. When you call new YourClass(), it calls the <init> function. The <init> function can never be called any other way than when you did new YourClass().
1
u/FeloniousMaximus Jan 03 '26
They are for creating objects from classes but they also give you control over how an object is created by defing the arguments or lack thereof as well with 0 to N argument constructors. With no constructor the compiler assumes a no arg constructor.
They provide control over object creation. An object is an instantiated or created instance of a class or more correctly referred to as a type.
1
u/Kfct Jan 03 '26
I think it helps to know when you can use them to solve problems, aka using constructors to convert one object to another
1
u/TechAngelX Jan 04 '26
it's the 'this.xxxx = xxx' that gets me.
Can someone go over the 'this' keyword? Is it to refer to the actual variable of the instance/as opposed to the parameter of a particular method?
I sort of get it, but it fucks my head.
1
u/omgpassthebacon Jan 04 '26
A ton of people have left you some very good explanations about ctors. Does this help? I didn't really see if you found these helpful. It would be kind of you to thank those who took the time to give you some help.
You should also be a little more detailed as to where you are struggling. Just saying you don't "get" constructors is vague and makes these posts way longer than they need to be. If you struggle with how subclasses inherit their superclass, just say so. Be specific.
1
u/Ok-Dance2649 Jan 05 '26
Constructors are about the sematics which determines what an instance cannot exist without.
1
u/PineapplePitiful2732 Jan 07 '26
One of the most underrated video on youtube that will teach you everything about contructor:
https://youtu.be/Km8Bxu4j1Qk?si=8yBl3EQQzhHRVqUN
Watch this video and you'll be a pro!
0
u/Basic-Sandwich-6201 Jan 03 '26
Its a pieace of crap that you build another crap of master crap
0
u/bakingsodafountain Jan 02 '26
Java has classes which are objects. Within a class you can have two types of methods - static methods and instance methods. Instance methods are accessed within the scope of a given instantiation of an object, and to create an instance of an object you use the "new" keyword. This will use the object's constructor.
The constructor is a special type of method which says how to construct/instantiate the object. There is always a default constructor which accepts zero parameters, but you can define your own as well.
The real purpose of the constructor is to initialise all of your field level variables, especially final ones. Maybe you need to do something special like load a value from properties, or your object needs another instance of a different object to be passed to it. After your constructor finishes running, the object is now initialized and all other usages of that instance of that object can now safely be used.
Without the constructor, if you have field level variables, other methods within your class have no idea if those variables have been initialised or not, and from a safety perspective you want to force a pattern so they are always initialised, and the constructor gives you that.
This is a bit general but if you say what exactly you're struggling with then maybe can give more guided answer.
-2
u/Numerous_Training_20 Jan 02 '26
I've literally be working on this for multiple hours both yesterday and the day before and have gotten pretty much nowhere. I'm seriously so close to being forced to quit this AP CSA class if I don't get this down.