I'll just point out abstract methods and interfaces are useful in situations where you might (perhaps) be writing a library and want other people to extend it and use it. Perhaps this library needs a callback that will be called when a button is pressed. In Java, you can't actually simply pass in a function to the library to be called when the button is pressed, like you can in Lua, or a bunch of other languages:
function onButtonPress()
print("Do stuff")
end
myLibrary.addButton("hello", 3, 4)
myLibrary.setButtonCallback("hello", onButtonPress) -- passing the onButtonPress function as a parameter
In Java, what you have to do instead is define an interface, or a class with an abstract method, and then subclass the abstract class or implement the interface, then create an instance of that new class, then pass that instance into the library. This way the library can be sure that the passed in object contains the callback method, and can be sure the program won't crash if it tries to call that method.
-- As part of the library
package com.mylibrary.button;
public abstract class ButtonCallbackClass {
abstract void onButtonPress();
}
-- As part of your code
public class MyButtonCallbackClass extends ButtonCallbackClass {
void onButtonPress() {
System.out.println("Do stuff");
}
}
public class Main {
public static void Main(String[] args) {
MyButtonPressClass callback = new MyButtonPressClass();
myLibrary.addButton("hello", 3, 4);
myLibrary.setButtonCallback("hello", callback);
}
}
You have to do this because Java is what's called a statically typed language (unlike Lua, and Javascript, and Python, which are dynamically typed), meaning that at compile time, Java must know the type of every variable (eg. String str = "hello";, instead of just str = "hello"), the return value of each function, the name and parameters of each function, etc... Unlike in Lua and Javascript, where you can just make that stuff up at runtime (while the program is running). Because of this, myLibrary
must know for sure that the button callback object you pass in has the function onButtonPress implemented in it, it's just the design of Java.
You can do the same above Java code using interfaces as well, which are probably nicer than abstract classes IMO.
Edited by GravityScore, 28 January 2014 - 04:18 AM.