0
Difference between having a constructor and not having one - Java
I'm still a bit confused as to why we would use a constructor. From my limited understanding, we use them to initialize all of the instance variables in our class so that whenever we make new objects of that class type we can have the same attributes (correct me if I'm wrong). However, my question is what is the benefit of using a constructor as opposed to simply just initialising like so: public class MyClass{ if(x > y){ private int speed = 200; private String colour = "red"; } if(x < y){ private int speed = 12 private String colour = "blue"; } }
7 Answers
+ 2
For one, what you wrote would cause an error.
In short, Constructors are the easiest, most optimal way of initializing the attributes.
Using constructors also avoids messy code that can end up confusing, and potentially program breaking.
What you wrote would need to be where you created the Object. For example in Main.
public static void main(String[] a){
int x = 1;
int y = 5;
MyClass a = new MyClass();
if(x > y)
{
a.speed = 200;
a.blahblah = 101;
}
etc...
}
Notice all the code for initializing attributes must be where you created the Object.
So, if you create the object in different classes, you may just be writing the same code over and over again.
Methods should be used to stop this kind of repetition.
This also breaks the idea of OOP.
Lets say I have a Frog class and all frogs cannot have blue eyes.
When I create a Frog I need to do:
String color = "Black";
if( !color.Equals("blue"))
{
frog.eyeColor = color;
}
This is procedural programming, NOT OOP.
If I placed that code in the Frog class it is a common trait all frogs have.
-All frogs cannot have blue eyes.-
if I wrote it outside the Frog class, it is no longer something Frogs share in common, rather just something the programmer is doing so Frogs don't have the same eye colour.
Also notice every attribute MUST be public or have a setter in order to initialize the attributes outside the class itself.
Difference:
Animal a = new Animal(1, "Cat");
vs
Animal a = new Animal();
a.age = 1;
a.type = "Cat";
Program Breaking reasons:
If Scanners had no constructors you could do this:
Scanner sc = new Scanner();
sc.inputStream = System.in;
sc.File = new File("Path");
Having an input Stream and File being read at once would cause lots of issues.
Or, if you were creating the Scanner to avoid issues you would do something like this:
public void setFile(File newFile){
if(inputStream != null)
return;
if(File != null)
return;
/*
If those aren't null the programming may not know why it's not working, so the you may need to throw an exception anyway.
*/
}
+ 2
Yes the approach you took looks easier.
My problem with it is that it's not maintainable.
For example, lets say all courses now had different letter grades.
You'll be changing it in all those if statements.
Or if one course is graded differently.
The if statements are easier though, I will admit that.
(For beginner's).
I used to actually code like that a lot. Atleast now I'm an expert on if statements. You will be too đ.
When you get more into OOP you'll get why it's used.
As for the constructors,
We would actually use physical entities, for example Skeleton, Creeper, Spider, etc.. in Minecraft would all be separate classes.
But here's some other real life examples of constructors:
The constructor will set the attributes of something that is born/created.
If I create a canvas, what size should it be?
Lets say 500, 500.
Ok, well:
new Canvas(500, 500);
The canvas will be born with that set size.
By born I mean it will come into the world I have created.
Lets say I want to make a chess game.
I want to be able to create pieces wherever I want, so I can make a Random version of chess.
The constructor could look like:
Pawn(int xPos, int yPos, char side)
{
....blahblah initialize stuff
// This code was more of a real example, rather than something you may understanding:
// (Unity Scripting đ)
Instantiate(
pawnGameObj, new Vector3(xPos, yPos, 0), null
):
}
Now I could easily make Pawns.
new Pawn(3, 6, 'W');
// white Pawn on C6
// 3 being C
Lets say I want to cover the entire board with black Pawns for fun, cause I'm looking for a cool varient of chess.
final int BOARD_SIZE = 8;
for(int i = 1; i <= BOARD_SIZE; i++)
for(int k = 1; k <= BOARD_SIZE; k++)
new Pawn(i, k, 'B');
How easy was that? đ.
Filled the board with black pawns.
Each Pawn was born (Created) on some x, y coordinate on the board. With a char representing its colour (white or black).
When I say we create the Pawn, this can be a 3D object that you can see.
+ 2
It was a constructor, just not used as it is supposed to be.
Constructors are for initializing attributes.
So, if you had a class called Student, and had his marks as instance variables, initializing them in the constructor.
Then that's kinda what its for.
You could just have the final score as an instance variable instead of all the marks if you really want.
(Instance variables are just non-static global variables)
You can still use the constructor for things you always want to do when an object is created.
(Or you could use an IIB block, but that's not covered in SoloLearns course)
+ 1
Yup!
Just note in Unity you may not create constructors a whole lot because of MonoBehaviour.
I usually create a method to act as a constructor if I need to pass parameters to the method.
+ 1
According to others, what I created wasn't really a constructor. Guess I'll have to keep researching.
0
I always believed there are some examples where you may want to use a mixture of both OOP and procedural as opposed to purely OOP. But I could be wrong, if you care to elaborate. In my actual example this is how I structured my code.
Firstly I created a 'studentGrades' class that would be the operator for deciding the grades of each student as we can see here:
https://code.sololearn.com/cE7q82nG0z2X
Then I created each student as a separate object (eg; Sam, John, Francis) which included different grades which would be passed to the parameter of the constructor within the 'studentGrades' class. I find that this approach is easier I will need to expand the program later on. But feel free to correct me if this completely wrong. I think the main difficulty of understanding how and why we use constructors comes from the lack of real life examples I suppose as we wouldn't be using physical entities such as 'animals' but rather more abstract components such as buttons, textfields and radio buttons, perhaps.
0
Thanks for the examples. Since I'm also learning unity game development it makes a bit more sense. I guess I just have to continue programming and eventually things will come together eventually as I progress. The important thing right now is I have a basic idea of what a constructor does and how we use it.