Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Tutorial] Abstract Class, Interface and Nested Class
Index -> Programming, Java -> Java Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
rizzix




PostPosted: Fri Oct 03, 2003 8:17 pm   Post subject: [Tutorial] Abstract Class, Interface and Nested Class

--Abstract Class--
An abstract class is a class that is not completly implemented, i.e it declares methods that need to be implemented by the subclass. You declare an abstract class by first explictly declaring a class abstract in its declaration and then declaring a method that has no body but terminated with a semicolon.

Like this:
Java:

public abstract class A {   // explicitly declared abstract
    int num;
    int getNum() {
        return num;
    }
    abstract void printMessage(); // declared but not implemented
}


You cannot create an instance of an abstract class. If you extend the abstract class and implement the method it declares then it is possible to create an instance of that subclass class you created.

NOTE: if the subclass of the abstract class does not implement the method declared in that abstract class, that subclass too will need to be explicitly declared abstract.


--Interface--
An interface behaves similarly like an abstract class, but it is not a class of any sort and yet it defines a type. It only declares methods and variables. It cannot have any method implemented. You create an interface just like you create a class, but instead of the 'class' keyword you replace it with 'interface'. This is an example of an interface:
Java:

public interface SortMethods {
    public void bubleSort();
    public void quickSort();

    final int MAX_VALUES = 100;
    final int MIN_VALUES = 10;
}


Just like an abstract class you cannot create an instance of an interface. You can create a class and declare it to implement that interface and then create an instance of that class. Once a class implements an interface it is as good as saying it has all the methods the interface declares as its members. Implementing the interface means implenting every method it declares. You don't have to implement every method, but if you don't then your class is not a so called normal class anymore, it is more like an abstract class since it has one or more methods only declared but not implemented and hence it has to be explictly declared abstract.
Java:

public class Test1 implements SortMethods {
    public void bubleSort() {
        ...
    }

    public void quickSort() {
        ...
    }

    public void undo() {
        ...
    }
}

public abstract class Test2 implements SortMethods {
    public void bubleSort() {
        ...
    }

    public void redo() {
        ...
    }
}

// Test2 is abstract while Test1 isin't since Test2 does not implement all
// the methods declared in the interface SortMethods it implements.


One subtle thing that is not quite obvious at first is that every instance of classes (or objects of classes) that implement interface, are also of the type the interface the class implements. This means this is valid code...
Java:

SortMethods s;
s = new Test1()// where class Test1 implements the SortMethods inteface
s = new Test3()// where class Test3 implements the SortMehods interface

s.bubbleSort()// valid since bubbleSort() is valid method for an object of type SortMethods.

s.undo();          //ERROR: Test1 has a method undo() yet it is invalid to
                       // call it, since s is of type SortMethods but
                       // SortMethods does not declare it.




--Nested Class--
A nested class is really a class defined within a scope of another class. It is treated as a member of that class and has full access to the members of its enclosing class, even the ones declared private. The only time you would be creating a nested class is when it makes sense to have a class that relies on an enclosing class for it's functions. For example a text cursor only makes sense in the context of a textbox widget.

There are two different types of nested classes: static and inner.

The static nested class is commonly known simply as a nested class. It is exactly what it's name defines it to be and behaves just like static methods and variables. Just like static methods (AKA class methods) it cannot refer directly to instance methods of it's enclosing class, altough it could call them through object instances.

The inner class is a nested class (static nested class) whose instance exists only within an instance of its enclosing class. It is treated like an instance method or variable of it enclosing class, thus it can refer to static methods and variables as well as instance methods and variables directly.

Java:

class A {             // <-- enclosing class

    static Class B {  // <-- nested class
        ...
    }

    Class C {         // <-- inner class
        ...
    }

    ...
}


A nested class (thus i'm talking about an inner class as well) is like any other class except for the facts above, thus it can also be declared abstract of final and will behave exactly the same way a normal class would.


--Anonymous Inner Class--
When programming GUI, you will be using a lot of these inner classes and at times you might come across nested classes in the API. But you usually will be writing inner classes for event handler etc. Since an event handler only makes sense in an instance of a component, it fits the discription of an inner class. But to save code there is a faster way to write out these inner classes: anonymous inner class.

An anonymous inner class is an inner class that does not have a name. They have a wierd syntax, but they do make coding cleaner and quicker. Take a look at this code:
Java:

import javax.swing.*;
import java.awt.event.*;     // <-- necessary to import ActionListener interface

class Test {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Press Me Example");

        JButton button = new JButton("Press Me Please");
        button.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    button.setLabel("Thank You");
                }
            }
        );

        frame.getContentPane().add(button);
        frame.pack()// automatically adjusts the size of the container
        frame.setVisible();
    }
}


First thing you will observe here is the wierd syntax that lets me declare a method inside another method. But NO! Thats not what i'm doing here. I'm declaring an anonymous inner class. The anonymous inner class is declared directly by creating an instance of an abstract class or an interface and implementing the methods they declare. And as you can see it has full access to the members of it's enclosing class thus it access the button member and set's it's label to "Thank You".
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Java -> Java Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: