Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this method need casting?

Tags:

java

casting

I've been writing a very basic musicplayer in Java for a school project, and I wanted to add a little sazz by implementing a volume slider. Basically, I read step by step how to do it, and it does work, but there is one element that I frankly don't understand, and that is the

(JSlider)event.getSource(); 

method. What I dont't understand is what seems to be casting. Why do I need to cast the event.getSource() to JSlider? And how can I even, since ChangeEvent and JSlider do not have a (to my understanding, at least) sub-class/superclass relationship?

Here is the method in full:

public void stateChanged(ChangeEvent event)
    {
        JSlider source = (JSlider)event.getSource();

        int volume = source.getValue();

        setVolume(volume);
    }
like image 997
SorenRomer Avatar asked Feb 13 '23 23:02

SorenRomer


1 Answers

The method signature is

public Object getSource()

Since it returns Object, it has to be casted to a JSlider to assign it to a JSlider variable. Everything is a subtype of Object; the compiler does not know that the returned Object is a JSlider.

like image 172
Someone Avatar answered Feb 26 '23 22:02

Someone