Help with Implement and Extends keywords
Hello,
I am slowly teaching myself Java. I have been learning the usage of Key listeners lately and one of the samples on the tutorial has me stumped in a way. I can re-create and manipulate the required code fine but although I know what I have to write I am not sure why 2 parts of the code are there and what purpose they serve:
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
publicclass KeyEventDemoextends JPanel
implements KeyListener,
ActionListener{
JTextArea displayArea;
JTextField typingArea;
staticfinal String newline ="\n";
public KeyEventDemo(){
super(new BorderLayout());
JButton button =new JButton("Clear");
button.addActionListener(this);
typingArea =new JTextField(20);
typingArea.addKeyListener(this);
//Uncomment this if you wish to turn off focus
//traversal. The focus subsystem consumes
//focus traversal keys, such as Tab and Shift Tab.
//If you uncomment the following line of code, this
//disables focus traversal and the Tab events will
//become available to the key event listener.
//typingArea.setFocusTraversalKeysEnabled(false);
displayArea =new JTextArea();
displayArea.setEditable(false);
JScrollPane scrollPane =new JScrollPane(displayArea);
scrollPane.setPreferredSize(new Dimension(375, 125));
add(typingArea, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(button, BorderLayout.PAGE_END);
}
/** Handle the key typed event from the text field. */
publicvoid keyTyped(KeyEvent e){
displayInfo(e,"KEY TYPED: ");
}
/** Handle the key pressed event from the text field. */
publicvoid keyPressed(KeyEvent e){
displayInfo(e,"KEY PRESSED: ");
}
/** Handle the key released event from the text field. */
publicvoid keyReleased(KeyEvent e){
displayInfo(e,"KEY RELEASED: ");
}
/** Handle the button click. */
publicvoid actionPerformed(ActionEvent e){
//Clear the text components.
displayArea.setText("");
typingArea.setText("");
//Return the focus to the typing area.
typingArea.requestFocusInWindow();
}
/*
* We have to jump through some hoops to avoid
* trying to print non-printing characters
* such as Shift. (Not only do they not print,
* but if you put them in a String, the characters
* afterward won't show up in the text area.)
*/
protectedvoid displayInfo(KeyEvent e, String s){
String keyString, modString, tmpString,
actionString, locationString;
//You should only rely on the key char if the event
//is a key typed event.
int id = e.getID();
if (id == KeyEvent.KEY_TYPED){
char c = e.getKeyChar();
keyString ="key character = '" + c +"'" +" " + e.getID();
}else{
int keyCode = e.getKeyCode();
keyString ="key code = " + keyCode
+" ("
+ KeyEvent.getKeyText(keyCode)
+") "
+ id +" I "
+ e.getID();
}
int modifiers = e.getModifiersEx();
modString ="modifiers = " + modifiers;
tmpString = KeyEvent.getModifiersExText(modifiers);
if (tmpString.length() > 0){
modString +=" (" + tmpString +")";
}else{
modString +=" (no modifiers)";
}
actionString ="action key? ";
if (e.isActionKey()){
actionString +="YES";
}else{
actionString +="NO";
}
locationString ="key location: ";
int location = e.getKeyLocation();
if (location == KeyEvent.KEY_LOCATION_STANDARD){
locationString +="standard";
}elseif (location == KeyEvent.KEY_LOCATION_LEFT){
locationString +="left";
}elseif (location == KeyEvent.KEY_LOCATION_RIGHT){
locationString +="right";
}elseif (location == KeyEvent.KEY_LOCATION_NUMPAD){
locationString +="numpad";
}else{// (location == KeyEvent.KEY_LOCATION_UNKNOWN)
locationString +="unknown";
}
displayArea.append(s + newline
+"" + keyString + newline
+"" + modString + newline
+"" + actionString + newline
+"" + locationString + newline);
displayArea.setCaretPosition(displayArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
privatestaticvoid createAndShowGUI(){
//Create and set up the window.
JFrame frame =new JFrame("testme");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane =new KeyEventDemo();
newContentPane.setOpaque(true);//content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
publicstaticvoid main(String[] args){
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable(){
publicvoid run(){
createAndShowGUI();
}
});
}
}
in the beginning during the class declaration:
publicclass KeyEventDemoextends JPanel
implements KeyListener,
ActionListener{
the part where itextends JPanel
andImplements KeyListener, ActionListener
Why are these needed? I mean if I want to use other methods I don't always need to extend or implement anything:
System.out.println("see");
for that I don't need to Import, Extend or Implement.... I am just confused, any clarification is appreciated.
JPanel, which you're extending, is a parent class. This means the class you're creating/writing will inherit all of JPanel's protected and public fields/methods.
Implementing an interface, in this case KeyListener and ActionListener are interfaces, means you're promising to implement the methods that the interfaces have defined.
The methods you need to implement are actionPerformed for ActionListener and keyPressed, keyReleased, key..something for KeyListener. Now if you really don't have any code for it, you could leave it empty, such as for KeyListener. But it wouldn't make sense to leave actionPerformed empty because that means you shouldn't be implementing ActionListener to begin with.
You should read up on object oriented programming, it will pave your way to understanding java easier.
When a class extends another class, it usually does so because you want the derived class to add or specialize behavior in the base class.
When a class implements an interface, it promises to have code for any methods declared in the interface.
You need to do some reading.
> Why are these needed? I mean if I want to use other
> methods I don't always need to extend or implement
> anything:
>
> System.out.println("see");
>
> for that I don't need to Import, Extend or
> Implement.... I am just confused, any clarification
> is appreciated.
System.out is automatically imported (I think, I don't know the actual details to that), but you are importing other packages for JPanel, ActionListener, KeyListener.
extending and implementing are very powerful and useful when used correctly. And to further my previous post, by having KeyEventDemo extending JPanel, KeyEventDemo is in fact a JPanel...it is also in this context a KeyListener and an ActionListener.
They're great for polymorphism.
If you try doing
KeyEventDemo demo = new KeyEventDemo();
if (demo instanceof JPanel) {
System.out.println("true");
}
if (demo instanceof KeyListener) {
System.out.println("true!");
}
if (demo instanceof ActionListener) {
System.out.println("true");
}
you will notice that it will print true for all those three conditions.
Thank you both for the replies, I know I need to do some reading. But whenever I read definitions for Implement and Extend they were somewhat confusing. I think I understand now for the most part.
Is the reason I can use System.out.println()without extending or implementing because it is a default access class (one that all classes have access to no matter what)?
>System.out.println("see");
>for that I don't need to Import, Extend or Implement
When you define a class that does not extend any other class, it implicitly extends java.lang.Object.
All java programs have implicit access to java.lang package. If you look at your javadoc and look into the java.lang package you'll see that the System class is there.
Realize also that extending, implementing and importing are very different things.
importing:
- gives you access to classes in other packages
extending
- creates an object that is same type as its superclass
e.g.
public class Ford extends Car{
}
Ford is a car and can do anything that a 'Car' can do.. plus other specific things.
implementing:
- just promises that you will provide some specific functionality
see here:
http://webchalkboard.tripod.com/java/lesson1/tute9.shtml
also see here:
http://java.sun.com/docs/books/tutorial/java/concepts/interface.html
> Thank you both for the replies, I know I need to do
> some reading. But whenever I read definitions for
> Implement and Extend they were somewhat confusing. I
> think I understand now for the most part.
>
> Is the reason I can use System.out.println()
> without extending or implementing because it is a
> default access class (one that all classes have
> access to no matter what)?
No that is not the reasong for it.
In your KeyEventDemo, you implement ActionListener because ActionListener has a method called actionPerformed(ActionEvent e)
Your KeyEventDemo needs this method to trigger some code when a low level action occurs (such as a button being pressed or what have you)
You extend JPanel because you want KeyEventDemo to be a JPanel (by inheriting JPanel's behavior etc.)
But notice how you have JTextArea and JTextField in your KeyEventDemo. You have instances of these objects in your class, so the only thing you have to do is import javax.swing, the package that these two swing objects resides.
Let me give you a better example of the meaning of extending
say there's an object/class called Animal. Animal has two methods called eat(), and sleep()
Now you creating/writing your own class called Dog. You know a dog can eat and sleep. So what you do is that you define your Dog class to extend Animal class which in turns means the Dog class will inherit the eat and sleep methods, this way you don't have to write the method and the code for eat and sleep, they're already inherited. However, you could optionally override them, in other words you redefine what they do, but their return type, modifier and method name needs to stay the same.
> Now you creating/writing your own class called Dog.
> You know a dog can eat and sleep. So what you do is
> that you define your Dog class to extend Animal
> class which in turns means the Dog class will
> inherit the eat and sleep methods, this way you
> don't have to write the method and the code for eat
> and sleep, they're already inherited. However, you
> could optionally override them, in other words you
> redefine what they do, but their return type,
> modifier and method name needs to stay the same.
If you are extending a class (whether abstract or concrete), you can change the modifier (public, private, protected, or package access). You just can't make it more restrictive. For example, you can change protected to public, but not public to protected.
> Is the reason I can use System.out.println() without extending or implementing because it is a
> default access class (one that all classes have access to no matter what)?
You can use the System class because all classes in the java.lang package are available without an import. The System class is in java.lang. 'out' is a public variable in the System class. 'println' is a method of PrintStream (the 'out' variable is a reference to a PrintStream object).
> Is the reason I can use System.out.println()
> without extending or implementing because it is a
> default access class (one that all classes have
> access to no matter what)?
The System class is bulit into the compiler and JVM. out is the variable name for one of the many objects of the System class. Here you are calling the println method of the out object.
The classes in the java.lang package are another example of classes built into the compiler and JVM.
Other J2SE classes have to be imported with the import keyword.
Classes of the Java EE also have to be imported with the import keyword.
Once classes are visible to the compiler, then you can use the extends or implements keywords in class declarations.
Wow, let me start by saying that of all the forums I have ever used those were the fastest and most comprehensive answers I have gotten. Thanks.
So to recap (making sure I truly understand)
EXTENDS
when I extend JPanel, I am declaring my class KeyEventDemo a subclass of JPanel and as such It inherites all the methods and variables of JPanel. I can if desired overide those methods with my own if I need or extend, as the name implies, the JPanel's functionality in my KeyEventDemo class....
IMPLEMENTS
By using the implement keyword I am 'agreeing' to use (implement) the methods of that interface. I am still required to import the correct package for the compiler to see the interface I have implemented. If I attempt to use the
actionPerformed() method without implementing the actionListener interface it will not be recognized and therefor will result in a compile-time error.
IMPORT
Allows me to access with out full classpath the methods and objects of any packages that I have impoted. The reason I do not have to do this with System.out.println() is because that is in a package that the compiler has default access to.
If I were to attemp to use JTextArea without first importing Javax.swing.*;
I would get a class not found error....
so, am I right or at least near right?
> IMPLEMENTS
>
> By using the implement keyword I am 'agreeing' to use
> (implement) the methods of that interface. I am still
> required to import the correct package for the
> compiler to see the interface I have implemented. If
> I attempt to use the
>
> actionPerformed() method without implementing the
> actionListener interface it will not be recognized
> and therefor will result in a compile-time error.
You can write an "actionPerformed" method without saying that you are implementing ActionListener. But, even if you have an actionPerformed method with the correct signature (name and parameter types), you won't be able to add your class as an ActionListener to a JButton. The compiler expects an ActionListener for "addActionListener". If you didn't tell the compiler that your class *is* an ActionListener by writing "implements ActionListener", it would give you an error on the "addActionListener(this)" line.
> IMPORT
>
> Allows me to access with out full classpath the
> methods and objects of any packages that I have
> impoted. The reason I do not have to do this with
> System.out.println() is because that is in a package
> that the compiler has default access to.
> If I were to attemp to use JTextArea without first
> importing Javax.swing.*;
> I would get a class not found error....
You never actually have to explicitly import anything. You could instead write all of the classnames out in full as:
public class KeyEventDemo extends javax.swing.JPanel
implements java.awt.event.KeyListener, java.awt.event.ActionListener
{
javax.swing.JTextArea displayArea;
javax.swing.JTextField typingArea;
static final java.lang.String newline = "\n";
...
}
Using import statements makes your code a little easier to write, because the names are shorter.
Actually, your main method has an example of using a class without explicitly importing it:
javax.swing.SwingUtilities.invokeLater(...);
> so, am I right or at least near right?
Yes. Some right, some near right. :)
> The System class is bulit into the compiler and JVM.> The classes in the java.lang package are another example of classes > built into the compiler and JVM.Sure, and little rocks float. Want to buy a bridge?kind regards,Jos
> EXTENDS
>
> when I extend JPanel, I am declaring my class
> KeyEventDemo a subclass of JPanel and as such It
> inherites all the methods and variables of JPanel. I
> can if desired overide those methods with my own if I
> need or extend, as the name implies, the JPanel's
> functionality in my KeyEventDemo class....
Not quite everything, only public and protected members. A private method or field will not be inherited.
and for implementing an interface, you agree to include the methods in your class, you don't necessarily agree to writing code for them.... The way you can look at it is that a programmer using your class may only be aware of its interface, and would expect that the class you wrote which implements the interface will provide those methods. Now whether the methods have a body or not is a different issue.
But overall I'd say you've picked up many essential things to java programming :)
Message was edited by:
youaresofakingwetodded