Friday, February 2, 2007

Lecture 12

Abstract Classes
  • Abstract class is a class that cannot be instantiated
    • only its children can be instantiated


Abstract Method
  • a method that is not defined in the abstract class
    • only its head is given

Interfaces
  • can be thought of as an extreme abstract class
  • used to group together classes with similar features into a 'type'
  • interfaces contain only abstract method headers
    • no instance fields
  • an interface is a description of how to interact with a group of related classes

Syntax

public interface myInterface

{
/*any method in here is abstract, it is assumed that it is abstract so you don't have to write the keyword 'abstract'*/

public void method(int a);
public int method2();
}

  • any class that implements the interface must override method, and method2

public class MyClass implements MyInterface
{

private int f;
public void method1(int a)
{

System.out.println(a)

}
public int method2()
{
return f;
}

}

  • you can create objects of type MyClass and treat them as type myInterface if necessary

public void interfaceMethod(myInterface in, int a)
{

int b;
in.method1(a);
b = in.method2();

}

  • it is possible to implement multiple interfaces

public class MyClass implements interface1, interface2
{
}

/* this would force MyClass to have all methods from both interface before it will compile */


  • it is possible to have inheritance within interfaces

public interface MyInterface

{

public void M1();
public void M2();

}

public interface myChild extends myInterface

{
public void M3();
}

  • a class that implements an interface but doesn't override one or more interface methods must be an abstract class
  • all unimplemented methods are automatically abstract

No comments: