Jump to content

extend?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
tautvilis

tautvilis

    Newbie

  • Members
  • Pip
  • 1 posts

import acm.program.*; 

import acm.graphics.*; 

import java.awt.event.*; 

public class MouseTracker extends GraphicsProgram {

	public void run() {

	 	label = new GLabel(""); 

		label.setFont("Times New Roman-36"); 

		add(label, 50, 50); 

		addMouseListeners(); 

	} 

	public void mouseMoved(MouseEvent e) {

		 label.setLabel("Mouse: (" + e.getX() + ", " + e.getY() + ")"); 

	} 

	private GLabel label;

}

When we import acm.graphics., we start being able to call Glabel constructor and invoke methods on it, true? Then why do we need to do "extends GraphicsProgram" when we have imported acm.program. package which has acm.program.GraphicsProgram class meaning me can call the method add(label, 50, 50).

Ok import is just a short way to access the class, but I could create Glabel object and call its method setFont in my class. Is this 0 funcionality? Finally why could not I do the same with add method, just access the class and call it without inherinting the class.

#2
SKGuitar17

SKGuitar17

    Newbie

  • Members
  • Pip
  • 3 posts
Well, there's a lot that I think could be said about this. I don't know how good of an answer I can give, but let's see what I can say. Firstly, about the import statement vs inheritance (extends). Here are some warnings/tips that may help. First, it is generally poor practice to import a whole entire package unless you plan to use most/all of it. I don't know what your plans are but you may want to consider only importing what you need. Secondly, it seems to me based on what you wrote you don't really need the extends clause, but I don't know exactly what functionality you are aiming for. Inheritance is a much overused practice. When you extend the functionality of a class, you gain all of the superclass' functionality when you usually don't need it. So you can probably be better off by using what you need from the currently extended class by initializing an instance variable in the constructor and using that to call its methods that you need. Hope I cleared something up for you! I bet someone can explain this WAY better than I can.