Domanda

I wrote the following class to fiddle around with Comparable/Serializable interfaces.

package testpro;

public class SerialTest implements Comparable {
    private int circleSize = 10;

    private int getCircleSize() {
    return circleSize;
    }

    @Override
    public int compareTo(Object o) {
    SerialTest object = (SerialTest) o;
    if(getCircleSize()>object.getCircleSize()){ // I can access object.getCircleSize() here, but it's private.. why?
        return 1;
    }
    else if(getCircleSize()<object.getCircleSize()){// I can access object.getCircleSize() here, but it's private.. why?
        return -1;
    }
    else{
        return 0;
    }
    }
}

I'm passing an Object o to compareTo() method, but getCircleSize() is private. So how is that possible, that I've got an access to this? I'm pretty sure C++ wouldn't let it go.

È stato utile?

Soluzione

Private means accessible from the same class only. And you are in the same class, after casting Object o to SerialTest object.

Altri suggerimenti

Private method are accessible within the class itself. Since both methods residing the same class, there no problem of accessing it.

The private modifier specifies that the member can only be accessed in its own class.

Check here for more details

private are not accessible by other classes. But within the class it is accessible for programming. Such as your code, you can use all the private identifiers or methods within the class while generating a result.

C++ also provides this function. You can easily use private method inside a class or method, to generate a response for a function call. It is simple and is legal!

You access to private member from same class. You override method compareTo() and in it you are accessed to your private member.

You can't do this with private member without accessor from each other class.

You can learn this from this link.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top