View Single Post
  #5   Spotlight this post!  
Unread 31-10-2009, 11:26
Jared Russell's Avatar
Jared Russell Jared Russell is offline
Taking a year (mostly) off
FRC #0254 (The Cheesy Poofs), FRC #0341 (Miss Daisy)
Team Role: Engineer
 
Join Date: Nov 2002
Rookie Year: 2001
Location: San Francisco, CA
Posts: 3,077
Jared Russell has a reputation beyond reputeJared Russell has a reputation beyond reputeJared Russell has a reputation beyond reputeJared Russell has a reputation beyond reputeJared Russell has a reputation beyond reputeJared Russell has a reputation beyond reputeJared Russell has a reputation beyond reputeJared Russell has a reputation beyond reputeJared Russell has a reputation beyond reputeJared Russell has a reputation beyond reputeJared Russell has a reputation beyond repute
Re: Question regarding interfaces

There are three main types of constructs in the Java world: abstract classes, concrete classes, and interfaces.

Abstract classes have at least one abstract method - this means that you cannot instantiate an object of an abstract class. For example, a "Vehicle" abstract class might have an abstract method "move()" - all vehicles can move, but they do it in different enough ways that you can't just make a Vehicle object and call move() - there's not enough information for that to be meaningful. Abstract classes can provide default implementations of methods, as well.

Concrete classes have no abstract methods, but they can inherit from abstract classes and provide implementations of abstract methods from the parent class. For example, a "Bike" class might inherit from "Vehicle" and provide a "move()" method. Now any function that takes a "Vehicle" class as an input can also take a "Bike" class and call the "move()" method, because it knows that all Vehicles can move. This is called polymorphism.

Interfaces are very similar to abstract classes - you can't instantiate them, only implement them. For example, a Bike might implement a "WheelieCapable" interface, since Bikes can do wheelies. WheelieCapable provides a "wheelie()" method that Bike must not implement. The difference is that while a concrete class can only inherit from one abstract class, they can implement MANY interfaces.

Code:
// Abstract class
public abstract class Vehicle
{
  // Abstract method
  public abstract void move();

  // Concrete method that can be overridden
  public void getIn()
  {
    ... do something ...
  }
}

public interface WheelieCapable
{
  public void wheelie();
}

public class Bike extends Vehicle implements WheelieCapable
{
  // Override the abstract method
  public void move()
  {
    ... do something ...
  }

  // Don't override the getIn() method - just use the default implementation

  // Implement the interface method
  public void wheelie()
  {
    ... do something else ...
  }
}
Reply With Quote