Is it possible to return a variable from an object-oriented class without using a function?

Asked

Viewed 188 times

2

I do not know if there is this possibility. Follow a code to assist in the question:

public class Square
{
    int side;

    public Square(int side)
    {
        this.side = side;
    }

    int getArea()
    {
        return side * side;
    }

    public static void main(String[] args)
    {
        Square square = new Square(5);

        System.out.println("Tamanho do lado: " + square + " / Area: " + square.getArea());
    }

}

Exit:

Size side: collections. Square@15db9742 / Area: 25

It is possible to exit this way without using a function get?

Side Size: 5 / Area: 25

  • 2

    Overwrite the method toString class Square and implement to return a string the way you want to display.

  • @but in this case is returning the same way, right?

2 answers

5

Yes it is possible:

class Square {
    public int side;
    public int area;
    public Square(int side) {
        this.side = side;
        area = side * side;
    }

    public static void main(String[] args) {
        Square square = new Square(5);
        System.out.println("Tamanho do lado: " + square.side + " / Area: " + square.area);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The object-oriented class may or may not have methods and not functions. They may have public fields as well. In this case you can take the value exists of it without a method. That’s what I did with the attribute area.

This has a difficulty, nothing serious, it can be what you really want. Whenever the value of the side changes for some reason, including the construction, this attribute needs to be updated so that whenever someone picks it has the correct value.

Note that the other attribute side used in the class does not have a visibility modifier, the ideal is always explicit. If you want it to be private (only the class can access it) state how private. If you want any part of the application to access its value state as public, as I did in the attribute area. In the case I put public to give access, as seems to be what you want, although the example is not correct.

In use at the time of asking for the side, I did not use the object as a whole, I used this attribute square.side.

Some people consider it wrong to access attributes directly without having a method to give indirect access. It depends on the application it makes sense to do just that. But there are cases that is an exaggeration and use an extra method only serves to disturb. See more in Property Vs variables (is C#, but the use of getter and Setter is equal).

Ideally the method main() should be in another class.

Although there are some recommendations for using the toString() i would not do that to return the side. Having the object printed and showing only the information on its side does not seem appropriate. Even if it is in this example, changing the composition of the class will be a problem. Have to conceptualize things right and implement according to the concept, otherwise a maintenance would make the code not be more suitable.

Trying to exemplify by taking the example in the comment in Caffé’s answer:

If you create a variable exemplo of the kind String. If only print exemplo, it will print the "contained" text in the variable. That is, when you print the variable you want it to print exactly the string. How the text is represented internally does not matter. In this case what is being printed is conceptually correct.

If you have a variable square of the kind Square, I mean, there’s a square in it, if you print it square, You’re supposed to print the square, whatever that means. If you only print the side of the square, it is a wrong representation of what the square is. Then you’ll use it hoping it prints the side, one day it needs to change and everything that existed doesn’t work anymore. This problem occurs because it is conceptually wrong.

In addition, the question talks about not using a function, the toString() is a function (method using correct terminology).

  • As I had said to @Caffé doubt is mere learning, it really reduces the understanding of the code. As you said, the main method should be in another class, imagine that this was the case and the variable

  • I accidentally pressed [Enter] ... and the side variable was private, it is possible to do this type of operation (square1 + square2), each with side 5 resulting in 10?

  • Or it makes everything too complex and unnecessary to rule out this kind of thing?

  • 2

    There is no technical limitation, beyond the wrong concept. Adding two squares (which makes no sense) is different from adding the sides of two squares. It’s not about being complex, it’s about being wrong. Even in learning, it’s not ideal to do it. Even if it was technically feasible.

  • 1

    I don’t think it’s a wrong concept. C# supports this by overloading operators. It is clear that the example in question may not justify, but the AP clarified the objective of it.

4


Implement in your class:

public String toString() {
    return side;
}

The rest of the code can stay as it is.

What happens is that the method toString() is called to convert your object to string when you concatenate it with other values in the method System.out.println. As you have not yet made an implementation of the method, the toString of the parent class is called, and what it does is show the name of the class plus the reference to the object (which is the output you are seeing on the console).

Maybe this solution is not a good idea in the sense of expressiveness of the code, but will do exactly what you are looking for. There must be a better solution, but then you need to explain your intention.

Edit:

Clarified that the idea is that the attribute side is in fact the representation of the object, just as the character string is the representation of a String object, so use the method toString in this way is a correct implementation.

And there is another way to represent an object by one of its attributes without having to explicitly invoke this attribute or its getter? Not, in Java there is no.

Examples of this resource in other languages would be the property default VB and C#operator overload, but Java does not have this feature. Java’s own types (String, Integer, Long...) do this using compiler and VM resources, not language resources. That is, you cannot achieve the same result in a class of your own.

  • I didn’t know it was possible to overwrite toString() +1. But my doubt still persists because I still have to use a function to present the variable of that class, let’s say the variable "represents" that class. This doubt came with the String class, when you create a new String("abc") and print it, in the console results in an "abc", without the need for a function to present this value. The expressiveness of the code really lowers, doubt is just learning.

  • 1

    Dude, Java does this with the String type using "magic", it doesn’t use language features itself. That is, you cannot reproduce this technique in your own classes. In VB.Net, for example, you can set a default property and in C# you can use operator overload to do this kind of thing, but you will still be writing a method - but in Java you only have toString even to represent the object. @Iagocoutinhocampos

  • 1

    @Iagocoutinhocampos Just a small correction: I wrote "VB.Net" for addiction, but it is VB that supports property default with the characteristic of representing the object. Property default in VB.Net is something else (equivalent to indexed property of C#).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.