Docsity

Java Enums and Inheritance: A Comparative Study, Papers of Computer Science

Toggle sidebar
bg1
C Sc 335 Section: 13- and 14-Sep, 2006
Enums
In older version of Java, the standard way to represent an enumerated type was like this
public class Font {
public final static int BOLD = 1;
public final static int ITALIC = 2;
// Creates a new Font from the specified name, style and point size.
public Font(String name, int style, int size)
}
Debug the following code. Why can't you read the message?
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ShowFontAsEnum extends JFrame {
public static void main(String[] args) {
out.println(Font.BOLD);
out.println(Font.ITALIC);
ShowFontAsEnum oneJableInAFrame = new ShowFontAsEnum();
oneJableInAFrame.setVisible(true);
}
public ShowFontAsEnum() {
super("Title: Font"); // Call JFrame's constructor
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 120);
Container cp = this.getContentPane();
JLabel label = new JLabel("This is a message of the emergency broadcast system");
label.setFont(new Font("Courier", 18, Font.BOLD));
cp.add(label, BorderLayout.CENTER);
}
}
Output
1
2
Use of a Java enum would have generated a compiletime error (an improvement).
public enum FontStyle {
BOLD, ITALIC;
}
public class Font {
// The current javax.swing.Font in Java allows integers to be passed as styles
// The frame above shows what can happen. This would have been better:
public Font(String name, FontStyle style, int size)
}
With an enum, you would see a compiletime error when trying to assign a FontStyle to an int
label.setFont(new Font("Courier", 18, FontStyle.BOLD));
The constructor Font(String, int, FontStyle) is undefined
pf3
pf4
pf5

Partial preview of the text

Download Java Enums and Inheritance: A Comparative Study and more Papers Computer Science in PDF only on Docsity!

C Sc 335 Section: 13- and 14-Sep, 2006

Enums

In older version of Java, the standard way to represent an enumerated type was like this

public class Font { public final static int BOLD = 1; public final static int ITALIC = 2; // Creates a new Font from the specified name, style and point size. public Font(String name, int style, int size) }

Debug the following code. Why can't you read the message?

import java.awt.Font; import javax.swing.JFrame; import javax.swing.JLabel; public class ShowFontAsEnum extends JFrame { public static void main(String[] args) { out .println(Font. BOLD ); out .println(Font. ITALIC ); ShowFontAsEnum oneJableInAFrame = new ShowFontAsEnum(); oneJableInAFrame.setVisible( true ); } public ShowFontAsEnum() { super ("Title: Font"); // Call JFrame's constructor this .setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); this .setSize(600, 120); Container cp = this .getContentPane(); JLabel label = new JLabel("This is a message of the emergency broadcast system"); label.setFont( new Font("Courier", 18, Font. BOLD )); cp.add(label, BorderLayout. CENTER ); } }

Output

Use of a Java enum would have generated a compiletime error (an improvement).

public enum FontStyle { BOLD , ITALIC ; } public class Font { // The current javax.swing.Font in Java allows integers to be passed as styles // The frame above shows what can happen. This would have been better: public Font(String name, FontStyle style, int size) }

With an enum, you would see a compiletime error when trying to assign a FontStyle to an int

label.setFont( new Font("Courier", 18, FontStyle. BOLD ));

The constructor Font(String, int, FontStyle) is undefined

Extending a class

Inheritance : The previous code shows that ShowFontAsEnum extends JFrame. The ShowFontAsEnum

class inherits all instance variables (including the private ones), the public methods, and the protected methods

of JFrame.

public class ShowFontAsEnum extends JFrame {

Calling the superclass constructor : ShowFontAsEnum is a subclass of the super class JFrame. You sometimes

need to call the superclass constructor. This is done with the keyword super, which may have arguments.

public ShowFontAsEnum() { super ("Title: Font"); // Call JFrame's constructor

Overriding methods : ShowFontAsEnum could override toString like this to return the string shown

@Override public String toString() { String result = "" + this .getClass(); result += "\n============\n"; result += super .toString(); // Call super class's toString with super return result; } class ShowFontAsEnum ============ ShowFontAsEnum[frame0,0,0,600x90,invalid,hidden,layout=java.awt.BorderLayout, title=Title: Font , resizable,normal, defaultCloseOperation=EXIT_ON_CLOSE ,rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,l ayout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSiz e=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]

Abstract classes : An abstract class is declared with the keyword abstract. It cannot be instantiated. An abstract

class virtually always contains abstract methods. An abstract method must be implemented by the subclass.

Here is one example of an Abstract class that requires subclasses to implement the anstract withdraw meyhods

(does this sound a like implementing an interface?).

abstract public class Account { private double balance; public Account( double initialBalance) { balance = initialBalance; } public double getBalance() { return balance; } public void debit( double amount) { balance -= amount; } protected void deposit( double amount) { balance += amount; } // All subclasses must implement this method in their own way abstract boolean withdraw( double amount); }

Project 3: SpamFilter: Where to begin

After importing the project, you will need to do is extend the abstract class.

public class RuleParser extends AbstractRuleParser { public RuleParser(String configFileName, String dtdFileName) { super (configFileName, dtdFileName); } // ... private List allowedAddresses = new ArrayList(); // ... @Override public List getAllowedAddresses() { return allowedAddresses; } } // END RuleParser

Then you can get the rootElement with this construction

RuleParser rp = new RuleParser("sample-rules-config.xml", "rules-config.dtd"); // You still need to call the parse method so it can throw exceptions later rp.parse();

Then parse method could the use the inherited method getRootElement from the superclass to get the

root of the DOM tree

public void parse() throws ParserConfigurationException, SAXException, IOException, ValidationException { Element root = this .getRootElement(); // ... parse the DOM tree to get the lists

If time permits:

 Download Spamfilter.zip from the 335 projects page, unzip it, import it into Eclipse

 Add class RuleParser to the package src.edu.arizona.spamfilter.xml and have it extend

AbstractRulerParser. Implement enough of RuleParser to print the three children of config

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ValidationException { RuleParser rp = new RuleParser("sample-rules-config.xml", "rules-config.dtd"); rp.parse(); // Show the three children of the root node config Element root = rp.getRootElement(); NodeList children = root.getChildNodes(); for ( int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child instanceof Element) { // Don't print whitespace System. out .print("child " + i + ") " + child.getNodeName()); System. out .println("='" + child.getTextContent() + "'"); } } } Output should be child 1) allowed-list='[email protected]@[email protected]' child 3) blocked-list='[email protected]@[email protected]' child 5) rules='.spam..Bad Text..Bad Text.[email protected]@[email protected].@.spam.' Without checking for instanceof Element (remove the if above) you see whitespace with new lines child 0) #text=' ' child 1) allowed-list='[email protected]@[email protected]' child 2) #text=' ' child 3) blocked-list='[email protected]@[email protected]' child 4) #text=' ' child 5) rules='.spam..Bad Text..Bad Text.[email protected]@[email protected].@.spam.' child 6) #text=' '