简体   繁体   中英

How can you invoke a method in Java class without using its class?

In OOP, I learned that we can call a method by using its class.

For example:

Person person = new Person();
person.methodA(); // calling the method in person class

Based on javafx docs of ListView (link) , The getSelectionModel() is a method of a class ListView (okay working). But the selectedItemProperty() method is the class of SelectionModel (link)

How can you call a method selectedItemProperty() without using its SelectionModel class? And what class does this addListener method came from?

myListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TodoItem>() {
///  blah blah blah
}
});

MultipleSelectionModel ( link ) extends SelectionModel ( link ), in which the selectedItemProperty() method is implemented.

selectedItemProperty() returns a ReadOnlyObjectProperty ( link ) instance, which extends ObservableValue ( link ), from which the addListener() method is coming.

As for how you can call these methods- this is just how inheritance works. The subclass ( MultipleSelectionModel ) inherits all of the properties of its superclass ( SelectionModel ). Thus any methods defined in SelectionModel you can call against a MultipleSelectionModel instance.

OOP Concept for Beginners: What is Inheritance?

When you call ListView#getSelectionModel() you are getting an object which is an instance of SelectionModel —more specifically, an instance of MultipleSelectionModel . Since you now have an instance of MultipleSelectionModel you can invoke methods present in that class, including inherited methods. This means you can do the following:

listView.getSelectionModel().selectedItemProperty().addListener(yourChangeListener);

Which is equivalent to the following:

MultipleSelectionModel<T> sModel = listView.getSelectionModel();
ReadOnlyObjectProperty<T> selectedItemProp = sModel.selectedItemProperty();
selectedItemProp.addListener(yourChangeListener);

As you can see, you are using the class of every object involved. The former, known as method chaining, is just shorthand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM