Thunda Wrote:Interfaces are like "classes", however, they are composed of only abstract methods. Abstract classes contain at least one abstract method. However, the advantage of an interface is that multiple interfaces can be inherited. Abstract classes, however, can provide concrete methods that do not have to be supplied by the subclass.
A static method or field is one that does not need the class object to be created, to be used. It is useful when you do not want to take up more space with objects.
Do abstract classes have to contain at least one abstract method?
Anyway, an abstract class is a class you can't create, but you're allowed to make subclasses of (extended classes).
As an example, let's say we have an abstract class Car. You cannot create a Car, because you must specify what kind of car it is. The abstract class can also have an extended abstract class as well. Say, we want to add in Mazda under the class Car. We cannot create a Mazda either, because we still need to specify what kind of Mazda we want. If we finally make a class MazdaMX_5, and create an instance of this, we're ready to go.
The Car class may contain special variables which a car needs, functions, and abstract functions. Say we have the function GearUp, which gears the current car one gear up. This function is abstract, as all cars doesn't gear in the same way, and all cars doesn't contain the same amount of gears. Thus this must be specified within a special type of Car, or a special brand, if all their cars have the same gear-mechanism.
A static method is a function which doesn't need to create instances of its element in order to do something. Say, Math.pow(x, y) for example. It's when you don't need more than the input-variables and constants to compute the value, or to do what it is ordered to do.
Morgana Wrote:Static methods are also useful when the operation is always the same, and you can't be bothered to create a new object all the time.
For example, Java.lang.Math.random() (or wherever the Math class is; I always have to look it up) is a static method. You wouldn't want to have to create a "Math" class every time you use it... Which would have fairly useless properties anyway.
Hmm, I never really though about that Math.random() was a static function. Funnily enough though, it creates a pseudorandom-generator and stores it as a static object within itself... wat.
Code:
private static Random randomNumberGenerator;
private static synchronized void initRNG() {
if (randomNumberGenerator == null)
randomNumberGenerator = new Random();
}
public static double random() {
if (randomNumberGenerator == null) initRNG();
return randomNumberGenerator.nextDouble();
}
Talking about... doesn't compute within my head. wahh.