Java Objects: Difference between revisions
(No difference)
|
Latest revision as of 21:55, 31 January 2011
Inheritance
Creating a subclass:
class SubClass extends SuperClass{}
Polymorphism
The subclass automatically inherits the superclass's methods. These may be overridden as needed. "Dynamic binding" refers to the fact that the version of an overloaded function which gets used is decided at runtime, based on the type of the object making the call. A subclass's constructor may use the superclass's constructor as super, but this must be the first command:
public SubClass(int n){
super(n-1); //SuperClass's constructor
...other setup...
}
Accessing superclass versions of methods from a subclass:
super.someFunction(String s);
Using subtypes and casting:super.someFunction(String s);
SuperClass a = new SubClass();
SubClass b = (SubClass)a;
(a instanceof SuperClass) //true
(a instanceof SubClass) //true
SuperClass c = new SuperClass;
(c instanceof SubClass) //false
Abstract Classes
Create an abstract class with
abstract class MyClass{}
An abstract class may contain abstract methods:
public abstract method1(int n);
Abstract methods don't have an implementation. Any nonabstract class that extends an abstract class must provide an implementation for any abstract methods.
Protected
A protected method is visible to subclasses (and to the current package).
Protected attributes should be used with caution.
Reflection
Given an arbitrary object at runtime, you can get all the information about its class: the type, fields, constructors, and methods. In addition, you can execute an arbitrary method.
Interface
This is Java's way of implementing multiple inheritance.
class MyClass implements Interface1{}
An interface can be instantiated (but not with new()). An interface doesn't have a constructor.
Interface1[] i1Array;
An interface can have subinterfaces:
interface SubInter extends SuperInter{}
Callbacks
Interfaces are the preferred way of having an instantiated object talk back to its instantiator:
class Instantiator implements ActionListener {
MyProcess mp;
public void doProcess(){
mp = new MyProcess(this);
mp.run();
}
public void actionPerformed(...){
...now the process is finished...
}
}
class MyProcess extends Thread {
ActionListener al;
MyProcess(ActionListener){...}
public void run(){
...do stuff..
//now call back
al.actionPerformed(...);
}
}