r/javahelp • u/Rafaelchavez • Oct 28 '20
Java seems redundant for a complete beginner when creates new objects
I'm sorry if this question seems stupid, I'm a complete beginner and the way Java constructs new objects seems redundant for me. Using the rectangle package for example:
import java.awt.Rectangle
Rectangle box = new Rectangle(5,10,20,30) So why do we write Rectangle twice? just writing
box = new Rectangle(5,10,20,30)or
var box = new Rectangle(5,10,20,30)isn't enough? writing this way it's clear that my object will be created from the Rectangle constructor
35
u/desirecampbell Oct 28 '20
The other responses here are correct, but have neglected to take into account that you're still just learning Java, and if you're asking this question then you haven't learned about polymorphism .
The reason you'd want to declare that the variable box is a Rectangle is because it might not be just a rectangle.
If you're learning Java from a course you'll definitely learn about polymorphism eventually, but suffice it to say that you could end up in a situation where you want to have a Rectangle named box but box might actually need to be a RedRectangle or a RotatingRectangle. You might see something like: Rectangle box = new RedRectangle(5,10,20,30);
5
Oct 28 '20 edited Oct 28 '20
Adding to this, all of the following are valid declarations
Collection<Integer> aCollection = new ArrayList<>(); Iterable<Integer> anIterable = new ArrayList<>(); List<Integer> aList = new ArrayList<>(); ArrayList<Integer> anArrayList = new ArrayList<>();And that is kind of a real life every day example.
The example uses generics (all those angular brackets), but you can ignore them for now, you will get there. Right now all you need to know is that the type (the left part) defines what you need while the instantiation (at the right) is the specific (and probably modifiable) way you provide such type.
Extra note. Starting with Java 10 this is also a valid declaration
var anArrayList = new ArrayList<Integer>();(As it has has been said by others)
9
u/DerekB52 Oct 28 '20
Writing var box is enough in newer editions of Java. What you are using there is something called type inference. Java can figure out you are making a Rectangle, and can automatically make a rectangle. Java couldn't do this several years ago. It's a relatively new feature.
It also has downsides. Like u/Kango_V mentioned, if you are using inheritance, and want an instance of Rectangle's parent class, you wouldn't want to use var.
16
u/Kango_V Oct 28 '20
What if you want an instance of Shape (assuming inheritance)?
Shape box = new Rectangle(5,10,20,30);
-8
u/ComfortablyBalanced Oct 28 '20
Yeah but that's not all the cases, I believe in 2020 compilers should be smart and flexible enough to allow us write both whether you want to use explicit type as you mentioned assuming inheritance or just using vars for something we know and assume is just a Rectangle class.
4
Oct 28 '20
Then you'll be happy to know Java has had "var" for years now, since JDK 10...
1
u/ComfortablyBalanced Oct 28 '20
I knew it already...
2
Oct 28 '20
So you believe that the way things are is the way things should be?
It's just a confusing comment then I think.
1
u/ComfortablyBalanced Oct 29 '20
Yeah, OK, I never realized why some communities are so toxic nowadays.
1
Oct 29 '20
Toxic?? Can you quote what I said that was toxic? Please, for my own knowledge.
1
u/ComfortablyBalanced Oct 29 '20
Not you, down-voters!
2
-1
u/HotRodLincoln Oct 28 '20
It's kind of funny to see Java take this from JavaScript. Should be fun when you get weird errors and chase it back to something you thought returned a number and turns out it returns the number as a String.
1
Oct 28 '20
It's still strictly typed and you still have to define the type so this still won't occur.
var myObj = new ArrayList<String>();
For example, above. myObj will still be a List type. I really think they only added it to make people who complain about Java being verbose happy, since it doesn't add any real functionality.
1
u/HotRodLincoln Oct 28 '20
You can infer it from a value
var str = "Java"orvar size = dom.getSize();You would think size would return a number, but it returns a
String. You won't get an error until you try to store it in an Integer, you can still for instance add it to things in the 7 + 7 = 77 sense for instance in your log and print statements, especially insidious if you're going to do size+=1 or something.1
Oct 28 '20
You as the reader of the code might think that, but the compiler will not allow it. The return type of getSize will determine the type of "var".
Any IDE worth it's salt will call this out immediately, and the compiler would complain on the first pass.
However if you ignore the IDE, AND you don't have unit tests AND you don't verify the return type of getSize before performing arbitrary operations on its result, then maybe this could bite you in the ass.
6
u/Swedophone Oct 28 '20 edited Oct 28 '20
var box = new Rectangle(5,10,20,30)
isn't enough? writing this way it's clear that my object will be created from the Rectangle constructor
Shouldn't it be enough in JDK10 or later which has local type inference?
https://docs.oracle.com/en/java/javase/15/language/local-variable-type-inference.html
6
u/ProseBeforeSnows Oct 28 '20
It’s not always the same. Take this for example:
List<String> myList = new ArrayList<>();Having the myList variable declared as a List interface type allows you to later assign it a different class type, while still requiring that the class type implement List.
myList = new LinkedList<>();This would not work if you initially declared myList to be of type ArrayList. Using List also prevents assignments like this:
myList = new HashMap<>(); // errorHope this helps.
2
u/HotRodLincoln Oct 28 '20
Also, since we're talking about Collections, Iterable is also a good one. You might not use Iterable yourself very often, but your data is manipulated as Iterables a lot.
2
u/lostinuhtceare Oct 28 '20
When you start building your APIs, it's always gonna be a great advantage to use an interface reference for your object than using the actual implementation.
In your case, let's say you have your own implementation of a Rectangle that impleents a shape interface. To refer to a rectangle object you could do
Shape ref = new Rectangle(); //with a var as you suggested it would always be a Rectangle reference and not the interface's
And in the future let's say you added another class called circle that implements the Shape interface, and another class triangle and another class square.
Would you rather you expose the Shape API or expose all these classes with tons of documentation for the users to worry about?
2
u/morhp Professional Developer Oct 28 '20 edited Oct 28 '20
var box = new Rectangle(5,10,20,30)is perfectly fine Java code if you're using one of the recent versions.
But another reason is that in real code, you're rarely using constructors. On more advanced code you're often using builders or factories. For example something like
List<String> items = Splitter.on(",").trimResults().splitToList("Paper, Pencil, Cup");
// items is now ["Paper", "Pencil", "Cup"]Also a large part of code is passing existing objects between classes and methods.
The minor redundancy when creating objects isn't really relevant and IDEs help you with typing, for example in IntelliJ Idea, I type
new Rectangle(5,10,20,30)then hit ctrl+alt+v
and IntelliJ adds
Rectangle rectangle = new Rectangle(5,10,20,30);automatically (the variable name is highlighted so you can type another one, if the default isn't too helpful).
2
u/sparkless12 Oct 28 '20
Well, Java is Type safe, and so variable declared has type and expects same type value. If I understand what is your problem with syntax, lookup what type safe means. u/msx was referring to update that allows you to create variable and assign type of it AND value of same type at same time.
Type Safe languages have ups and downs tied to the concept, it's just about getting used to it.
Just sidenote, if you are learning AWT for sake of Graphic based UI, I would skip to JavaFX. It's modern GUI framework, you'll learn same amount as with AWT and you'll not be gagging how ugly the UI is after x hours of hard coding.
1
u/Java_Cowboy Oct 28 '20
You wont always call to the same class that houses an expected constructor. I'm assuming this is something for a course so eventually they may introduce Interfaces. Typical programing would have you call to a Interface to limit the amount of methods given to a client. For instance we could have something that looks like
RectangleInterface box = new Rectangle(5, 10, 20, 30);
This just means the methods available to the main class are anything that is public in the RectangleInterface. Also note that Rectangle will be implementing or extending RectangleInterface.
1
u/jocularamity Oct 28 '20
The declaration type and instantiation type don't have to be exactly the same, just related by inheritance. E.g.:
Shape box = new Rectangle(5,10,20,30);
Shape circle = new Circle(someRadius);
1
u/msx Oct 28 '20
You're right and the Java team addressed the issue in latest Java versions, you can use "var" now. All other use cases described by others are still permitted obviously, so it's win win.
1
u/HotRodLincoln Oct 28 '20
Inheritence.
You could say:
Person Sam = new Student();
Person John = new Teacher();then in a loop you can say:
for( currentPerson : personList )
{
println(currentPerson.sayName() + ": " + currentPerson.sayProfession );
}and use polymorphism to have different functions called.
-8
u/evils_twin Oct 28 '20
instead of this
import java.awt.Rectangle
Rectangle box = new Rectangle(5,10,20,30) you could write this
java.awt.Rectangle box = new java.awt.Rectangle(5, 10, 20 , 30)1
1
•
u/AutoModerator Oct 28 '20
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
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: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Code blocks look like this:
You do not need to repost. Just use the edit function of reddit to make sure your post complies with the above
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.