Inheritance, Inner Classes and Interfaces

Inheritance

Example, an applet create a super class based on the Applet class using the extends keyword-

import java.applet.Applet; //File Name is applet.java
import java.awt.*;
public class applet extends Applet //Here applet is a user defined class and Applet is library class of java
{
public void paint(Graphics g) // Here Graphics is a library class of super class Applet
{
g.drawString("Hello from Java",60,100); //Here drawString is a library method of class Applet
}
}

Interface

Suppose you want to create an applet that handles button clicks. To create a standard applet, you can derive a class from the java.applet.Applet class, and to handle button clicks, you use another class, ActionListener. Therefore, it looks as through you'll have to base your applet on the Applet and ActionListener classes.

In this case, that means you can extend your applet from the Applet class and use the implements keyword to add the button-click handling.

Example:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class clicker extends Applet implements ActionListener{
TextField text1;
Button button1;

public void init(){
text1=new TextField(20);
add(text1);
button1=new Button("Click Here");
add(button1);
button1.addActionListener(this);
}

public void actionPerformed(ActionEvent event){
String msg=new String("Welcome to Java");
if(event.getSource()==button1){
text1.setText(msg);
}
}
}

Inner Class

Java now lets you creates within classes, and the enclosed class is called an inner class. You might not see much need for defining classes within classes now, but it will become more apparent when we start handling user interface events, such as when the user closes a window.

Events are handled with interfaces and when you implement an interface, you must also provide implementations of several abstract methods inside the interface. To make this process easier, java provides adapter classes (Inner Class)

Example:

AppFrame.java file contains-

import java.awt.*;
import java.awt.event.*;

public class AppFrame extends Frame
{
public void paint(Graphics g)
{
g.drawString("Hello from Java..",60,100);
}
}

App.java file contains-

import java.awt.*;
import java.awt.event.*;

public class App
{
public static void main(String[] args)
{
AppFrame f=(new AppFrame());
f.setSize(200,200);
f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});
f.show();
}
}