20-CS-4003-001 Organization of Programming Languages Fall 2017
Inheritance

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code    

Use Services Provided by Other Classes

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;

class java_2Frame
   extends JFrame implements ActionListener {
   JTextArea text;
   JButton go;
   int i;

   public java_2Frame () {
      setLayout(new BorderLayout());
      add("Center",
          new JScrollPane(text = new JTextArea()));
      JPanel p = new JPanel();
      p.setLayout(new FlowLayout());
      p.add(go = new JButton("Run it"));
      add("South", p);
      go.addActionListener(this);
      i = 1;
   }

   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == go) {
         text.append(i+" ");
         if ((i++ % 10) == 0) text.append("\n");
         int p = text.getDocument().getLength();
         text.setCaretPosition();
      }
   }
}

public class java_2
   extends Applet implements ActionListener {
   JButton go;

   public void init () {
      setLayout(new FlowLayout());
      add(go = new JButton("Applet"));
      go.addActionListener(this);
   }

   public void actionPerformed (ActionEvent evt) {
      java_2Frame jf = new java_2Frame();
      jf.setSize(450,300);
      jf.setVisible(true);
   }
}
 -  An attribute of object-oriented languages is the ability to inherit services from other classes. In Java this is handled by extends. In the code to the left class java_2Frame inherits the ability to display a JTextArea and JButton from the JFrame class.