Reputation: 3318
Im currently learning Java and Im now facing the following error
Object label1 = addLabel("First number");
And my addLabel function
public Object addLabel(String text)
{
JLabel label = new JLabel(text);
add(label);
return label;
}
I was wondering why I cant access any of the methods of label on my variable label1 if Im returining it as an object?
Ex : label1.setBounds(...);
Upvotes: 3
Views: 155
Reputation: 11832
There's a difference between the type of object that exists in memory, and the type of reference you have to it.
In this case, your object in memory is a JLabel, but your reference is an Object - so code using this reference can only see methods available in Object.
If you chose to return your object as a JLabel and store the reference as a JLabel, your subsequent code would have access to the methods in JLabel.
Upvotes: 0
Reputation: 285401
You can only access the methods that the variable has available, and Object has none of those methods. That is why you should not be using Object in this way. Yes, the object the variable holds is a JLabel, but the compiler knows that the variable can hold an object of any type, and so to be safe, only allows Object method calls.
Possible solutions:
((JLabel) label1).setText("Foo");
label1
as a JLabel variable and declare addLabel
to return a JLabel.Upvotes: 6
Reputation: 201439
Because you have erased the type, you need to return a JLabel
to use it as a JLabel
-
public JLabel addLabel(String text)
{
JLabel label = new JLabel(text);
add(label);
return label;
}
and then
JLabel label1 = addLabel("First number");
Upvotes: 4