Programming Java: Pass object into static method?

New object a of the class Auto_ created

=> a.output(); doesn't output anything to the console. Why not?

=> System.out.println(a) calls toString(). That's it!

=> Auto_.getsOut(a) works. This is a static method and is passed to an object of the class Auto_ (here Auto_ auto).

Why does this work here now, that I can call the attributes of the object or parameter in the System.out.println(auto.brand + " " + auto.color ….)?

I'm using a static method, right?

1 vote, average: 1.00 out of 1 (1 rating, 1 votes, rated)
You need to be a registered member to rate this.
Loading...
Subscribe
Notify of
3 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
BigMett
1 year ago

In Java, static methods can only operate at class level and do not have direct access to instance variables or methods. If you try to call a non-static method like a.gibAus() in a static method, this will not work because you have to access a specific object to execute the method.

With regard to System.out.println(a), this works because the System.out.println() method calls the toString() method of the transferred object. The toString() method is usually implemented in such a way that it returns information about the object, eg the class name and possibly some attribute values.

The use of Auto_.sentAus(a) is a static method that receives an object of the Auto_ class as a parameter. In this method you can access the attributes of the transferred object auto as you have a specific object to which you can refer.

It is important to note that a static method does not “own” a specific object and therefore cannot access any instance variables directly. However, it can access instance variables by referring to a specific object that is transferred as a parameter.

PachamamaSquaw
1 year ago
Reply to  BigMett

Did you write/write this whole text yourself?

orochi02
1 year ago

I assume that your constructor does not properly construct the object and therefore nothing is printed