Friday, August 10, 2012

Java Interfaces and Abstract Classes

These are some notes from a java/c class I took 

Interfaces

  • There are like abstract classes
  • Their default types for methods are public abstract
  • None of the methods are implemented
  • Fields are automatically assumed to be public, static, and final
  • A class that implements an interface can be used as a type to initialize the interface type
  • For instance, Playable p = new TicTacToe();
  • This forces classes implementing an interface to follow it and classes using these implementers can assume that methods from the interface can be used
  • Interfaces are useful when disparate classes need to play common roles
  • You cannot extend more than one class, but you can implement multiple interfaces
  • Interfaces can be created for each major function, so a child class can pick and choose which interfaces it needs; this is better than using a single interface for multiple functions, since you would have to create dummy functions for ones you don't need
public interface Playable{ //the playable interface is stored in Playable.java like classes
  void play();
}

public class TicTacToe implements Playable{
  public void play(){//code here
  }
}


Abstract Classes

  • Are used to define general methods and fields for subclasses
  • They cannot be instantiated, but you can have abstract class variables that are assigned to subclassses (of an abstract class)
  • Every abstract method has to be overriden
  • Not every method has to be abstract
  • Private methods cannot be abstract
  • The constructor can be implemented (and other methods as well)
  • You can have an abstract class with no abstract methods
public abstract class Ball{
public abstract int hit(int batSpeed);
}
public class BaseBall extends Ball{
public int hit(int batSpeed){//code here}

No comments:

Post a Comment