#Java override

1 messages · Page 1 of 1 (latest)

empty marsh
#

i get "Method does not override method from its superclass"

public class MallardDuck extends duck{
    @Override
    public static void display(){
        System.out.println("A mallard duck appears");
     }

}
signal sleetBOT
#

<@&987246399047479336> please have a look, thanks.

empty marsh
#

base class

package com.company;

public class duck {
    public static void quack(){

    }

    public static void swim(){

    }

    public static void display(){
        System.out.println("A duck appears");
    }
}
#

what am i doing wrong?

hallow quail
#

Static methods in java are not (and cannot be) 'virtual'. They aren't inherited from a parent and cannot be overridden.

Unfortunately Java has two places (that continue to exist for backwards-compatibility) that make this confusing. And child static method can therefore 'shadow' a parent static method.

Calling a static method using a subclass makes it look like the method is inherited. And calling a static method from a reference makes it look like it should use inheritance too

class Parent {
   static void m() { System.out.println("Parent"); }
}

class ChildWithoutM extends Parent {}
class ChildWithM extends Parent {
   static void m() { System.out.println("Child2"); } // 'shadows' the Parent m()
}

...

ChildWithoutM.m(); // this is actually compiled as Parent.m() and prints "Parent"
ChildWithM.m(); // this prints "Child2"

Parent o = new ChildWithM();
o.m(); // this is actually compiled as Parent.m() and prints "Parent". It uses the declaration type of o.

It is popular, using build-tools and/or continuous-integration, to enforce that static methods are called only via class literals, and only from the declaring class so that this confusing usage is not allowed.,

#

There are languages in which virtual class methods exist - but it's rare, and requires that you can declare variables of class types and class-families. Java doesn't have these concepts (and they're only occasionally useful).

empty marsh
#

so the output should be child2?

hallow quail
#

No. That's the illusion this unfortunate grammar feature implies. But static methods are not inherited. The type of the reference o is Parent and so Parent.m() is what compiler resolves.

empty marsh
#

oh , i see , thank you

#

also , do i have to put the class files inside the com.company "package?" folder?

#

or i can put then directly in src folder?

swift niche
#

all classes live inside a package

#

so MallardDuck is in the com.company package

#

and you probably see a package com.company; at the top

#

if you put it right under src and remove that line it is in "the unnamed package"

#

which works, but small caveat - code in named packages can't import from the unnamed package