r/learnjava • • Nov 05 '24

Why is the syntax for creating an Object like this "classname var = new classname()"

It always bothers me to understand the syntax for creating an instance of a class (object).

Its "classname var = new classname();"

Why isnt it just
- var = new classname();
or

- new var = classname();

I mean the name of the class is already statet. Why repeat it? Seems so redundant.

3 Upvotes

20 comments sorted by

•

u/AutoModerator Nov 05 '24

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 - best also formatted as code block

  • 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.

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:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

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.

43

u/aqua_regis Nov 05 '24

You are seeing this wrong.

It's: datatype variableName = new Constructor()

You could call it as var myName = new ClassName(); if you want to save a few characters.

Yet, the orignal syntax comes into play when you work with Class hierarchies. You can use a parent class as data type and call the constructor of a sub class.

0

u/jimmyberny Nov 05 '24

I consider this as best argument, to keep the long syntax. Define type as a superclass/inferface and instance with a subclass.

OneInterface instance = new Subclass(); // methodThatReturnAnySubclassOrImpl();

For everything else they have created some shorter syntax, I have never used. I think Kotlin does this always.

21

u/OneBadDay1048 Nov 05 '24

Java is a strongly typed language. Knowing the types makes your code easier to read, maintain, scale up, etc etc. You are free to use var to declare new local variables if you are using a Java version newer than 10 but you will lose out on these benefits. When your applications become more advanced than simple beginner projects, you may miss the extra verbosity that made your code easier to understand.

I mean the name is already stated. Why repeat it?

classname var = new classname();

This is not even really technically correct anyway. Classname is the type declaration where as classname() is a call to the constructor of that class which just happens to repeat that information based on naming conventions. Say you have another method that returns an object of type 'classname' like in this example:

classname obj = methodName();

Here, the information is not duplicated.

2

u/ustclass_18 Nov 06 '24

Not me just realising now what ‘strongly typed’ means ……. I’m a moron 😑

-7

u/ajorigman Nov 05 '24

Each to their own but I personally find var a lot more readable than the wall of text created by explicitly typed variable declarations.

Java is a verbose language as we know and I think any mindful effort to keep code concise goes a long way.

Some developers seem to go out of their way to make things as verbose as possible and it’s what gives Java a bad name in some circles as it is a chore to read

ContextAwareOutboxPublisherFactory contextAwareOutboxPublisherFactory = new ContextAwareOutboxPublisherFactory();

Is completely unnecessary, you are not losing any readability by doing the following, in fact I’d argue this is a lot more readable:

var factory = new ContextAwareOutboxPublisherFactory()

6

u/OneBadDay1048 Nov 05 '24

Yes, in that very specific isolated piece of code, var does improve readability. That is exactly the point of var. But going thru your project only using this method like OP hints at…that could be a recipe for an awful code base.

-2

u/ajorigman Nov 05 '24

I do only use var when possible. I find it creates a very readable style with less visual noise. Not saying that the alternative is wrong, coding style and design is often subjective with no right or wrong. It’s about trade offs and personal preferences in many cases.

5

u/TheMrCurious Nov 05 '24

Depends on the company you work for and how much you care about documenting the intent, long term readability, and maintainability.

2

u/akthemadman Nov 06 '24

I am very interested in seeing some of your code. Do you have a github project that is representative or something else I could take a look at? If there is nothing readily available online, some representative excerpt put onto "a pastebin" (~100 lines, not ~10 lines) would be really appreciated.

1

u/ajorigman Nov 06 '24

Hey mate, id be happy to share some code, although would rather not share my personal GitHub and don’t really have any other code examples.

But in general I use Java 21+, I try to keep my classes and methods small and easy to unit test. As stated I use var almost exclusively when declaring local variables and where possible I prefer streams over loops, expressive lambdas and switch statements over non-expressive ones and method references over lambdas.

Judging by the downvotes I’m clearly in the minority in this sub with some of my opinions, but these are mostly stylistic choices, no right or wrong options usually unless you’ve done something horribly unreadable or slow. And consistency is key, so would always fall in line if I was at a company with a different style guide.

My last two companies have used style guides similar to the above, both large backend teams, 100+ micro services.

2

u/akthemadman Nov 06 '24

The downvotes situation is definitely a bummer, as I often have to open up downvoted comments manually just to see some interesting content. Though there is nothing to do about it beyond personally sticking to the ways of reason and hoping it spreads from the personal influence sphere.

But that is besides the point: Thanks for painting a clearer picture, I got where you are at, no need to go for the trouble of sharing additional code.

What support for var does your dev environment provide, i.e. how much effort do you have to put to get the type information for a var? I think that might be one of those separation points. A single key-combination to immediately toggle an inline hint for the type is golden, while mousing over the var or method call is a huge pita.

Then there is the argument to be made of not having access to the dev environment at all times, like when browsing github or even worse alternatives (in regards to inspection features), at which point not even mousing over might help. I guess you are not often in these situations then? Or do you think the trade-off is easily worth it in the context you are active in?

2

u/ajorigman Nov 06 '24

By dev environment do you mean the ide? I’ve always used IntelliJ. Have used both community and ultimate. Both are good, there’s not a huge difference between the two apart from additional spring wiring help and other language support. IntelliJ makes navigating code trivial to the point where the var thing is a non issue. Haven’t used other IDEs for Java but I’m sure some others are good too.

I do get your point that if you were reading in something less optimised like GitHub or bit bucket, then the additional typing would be welcome. But imo reading code in the browser should be done to quickly check or reference something. For anything serious, like code reviews, debugging, understanding a code base, etc, you should always check out the code in your chosen IDE and dedicate the time to going through it properly to fully understand it.

1

u/Stack_Canary Nov 05 '24

I think it’s fine to use var or val (lombok) when the class is explicitly stated:

final var factory = new MyFactory();

However, if the type is less obvious I would be explicit:

final MyFactory factory = methodWithReturnValue();

1

u/ajorigman Nov 05 '24

Yeah nothing wrong with that.

Both styles are valid.

9

u/Fun-Sample336 Nov 05 '24 edited Nov 05 '24

You can create new objects as a supclass of a class. For example:

Food f = new Meat()

You need to use this for example when you have many types of food and you put all of them into a Collection (like List<Food>). So the type preceeding the variable isn't redundant.

If you want to declare your variable with the same type as the object you create and assign to the variable, you can simply write var instead. For example:

var f = new Meat()

Then f has the type Meat.

3

u/MrNighty Nov 05 '24

I'm not 100% sure if this was intended or not but don't use "var" as an example for a variable :D

"var" could be actually something you are looking for (https://openjdk.org/jeps/286).

If you want to create a new object (for local variables) you could just write (Java 10+):

var foo = new MyFooClass();

1

u/Cyberkender_ Nov 05 '24

Correct. Data type inference was introduced in Java with version 10. It can be used on local scope variables and makes it easier to write code without explicitly indicating the type. Although it can sometimes be an advantage, it can make certain parts of the code more complicated to understand:

for(int I=0;I<10;I++){ var z=metodoX(); metodoY(z); z.doThings(); }

In this case we don't know anything about the type of z and the code may look more confusing..

1

u/Quantum-Bot Nov 06 '24

Evidently lots of other people were also annoyed by this, which is why C# (Microsoft’s response to Java) actually does allow you to do what you suggested! Either of these are valid syntax in C#:

var myVar = new MyClass();

MyClass myVar = new();

There is a good reason why Java has you specify both the variable data type and the constructor type, and that’s because of something called polymorphism.

Polymorphism is the practice of constructing an object of one class, but treating it like something else.

If a class inherits from another class, you can create an object of the child class, but assign it to a variable of type parent class. For example:

Phone myPhone = new GalaxyNote7();

As for why you’d want to do this, one example is if you want to store multiple objects of different types in a list together so you can iterate over all of them:

ArrayList<Phone> phones = new ArrayList<Phone>();
phones.push(new GalaxyNote7());
phones.push(new iPhone13());
phones.push(new Pixel8());
for(Phone p : phones)
{
    p.call();
}