Sheila Mathews
Sheila Mathews

Reputation: 9

Abstract Class Error in Java

I'm new to Java and I'm running into a compile error I cannot figure out.

Chapter5Debug is not abstract and does not override abstract method itemStateChanged(java.awt.event.ItemEvent) in java.awt.event.ItemListener

public class Chapter5Debug extends Frame implements ItemListener
       ^

Can anyone help me understand what I need to do to fix this?

Appreciate the help!

Sheila

Upvotes: 0

Views: 4248

Answers (4)

Vivek Vermani
Vivek Vermani

Reputation: 2004

ItemListener is an interface and hence implementing ItemListener means you either you will have to provide the implementation in Chapter5Debug

or

You can make Chapter5Debug abstract and then provide the implementation in the class inheriting Chapter5Debug.

Crux is that if you implementing an interface, You can't get away by not providing the implementation. Either you have to provide it there itself or carry it to the child classes.

Upvotes: 0

nullPainter
nullPainter

Reputation: 3016

To elaborate on @kevolution's answer:

public class Chapter5Debug extends Frame implements ItemListener {
    public void itemStateChanged(ItemEvent e) {
        // Write your method here
    }
}

An abstract class is one which is just like a regular class but can contain some 'stub' - or abstract - methods. These are methods which need to be implemented by the class extending the abstract class. In this case, itemStateChanged() is marked as abstract, meaning that you need to declare it.

Abstract classes are useful for when you're writing code which you need the caller to provide guts in some ways. In this case, Java cannot know what to do when the item's state changes, but it can do a whole lot of other stuff. The other stuff is in regular methods in the Frame class, and these call the itemStateChanged() method - which will then invoke your own handling code.

Upvotes: 1

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

You need o implement itemStateChanged(ItemEvent) within Chapter5Debug

example code

public class Chapter5Debug extends Frame implements ItemListener{

//where initialization occurs

checkbox.addItemListener(this);

public void itemStateChanged(ItemEvent e) {

if (e.getStateChange() == ItemEvent.SELECTED) {
    label.setVisible(true);
    ...
} else {
    label.setVisible(false);
}

}

}

Upvotes: 0

kevolution
kevolution

Reputation: 51

You have to remember that if ItemListener is abstract, then you will need to implement all the methods inside ItemListener. If you want to keep your current structure, you can just add an empty itemStateChanged method to your Chapter5Debug class.

Upvotes: 1

Related Questions