简体   繁体   中英

java class cannot override size() from Component?

Can we not override size() from the Component class in Java?

This is in a simple class, myPanels is an ArrayList that has been initialized in the constructor.

    /**
 * Returns number of panels
 */
@Override
public int size(){
    return myPanels.size();
}

Error reads: The return type is incompatible with Component.size()



EDIT - SOLUTION

Solution was to choose a different method name. Used something other than 'size()'

If you want to find a way to reliably change the size of a GUI component, then you should override getPreferredSize() instead of dealing with size or getSize() . This way your components will play nice with most layout managers.

Else if you're using this method to return the size of an ArrayList that it holds and not to try to set the visualized size of a component, then give your class a method to do this, but don't name it getSize() as that will confuse both other coders and the compiler. Instead name it getMyPanelSize() or something similar.

Assuming you're overriding java.awt.Component.size()

A: It's been deprecated since Java 1.1, use getSize() instead.

B: Either way, it must return a Dimension

The size() must return Dimension, and is deprecated since 1.1

I think you want to override the getSize() ?

Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.

The size() method of Component returns an object of type Dimension - which means you can't return an int.

An approach is to just name the method something else, like panelsSize() . Another is to return a Dimension .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM