简体   繁体   中英

Call method from child Class

I am trying something like this:

public class Dog {
}

public class Cat extends Dog {
    private void mew() {
    }
}

Dog d = new Dog();
d.mew();

During runtime d will contain a cat object due to other methods but I can't compile.

In should initialize Dog with Cat instance (or Stone with SpecialStone instance):

Stone s = new SpecialStone();

Then you can call the method on your SpecialStone (This can work only if you initialize parent by child class):

if (s instanceof SpecialStone) {
   (SpecialStone)s.specialMethod();
}

Another way is use of polymorphism:

public class Stone {
   public void specialMethod() {

   }
}

public class SpecialStone {
   @Override
   public void specialMethod() {
   }
}

But it will add specialMethod to every instance of Stone

Its the other way around.

Dog is a parent class, so it actually doesn't know that some class Cat extends it, and it doesn't know about the methods of a classes extending it.

However Cat extends Dog and it knows about all non-private methods of a Dog + its own methds.

So you couldn't call mew() from Dog .

Use an interface that defines the methods for a "Stone" and then use different implementations for a NormalStone or a SpecialStone. See my example:

public interface Stone {
    int getValue(); 
}

public class NormalStone implements Stone {

    @Override
    public int getValue() {
        return 1;
    }
}

public class SpecialStone implements Stone {


    @Override
    public int getValue() {
        return 100;
    }
}

public class Game {

    public static void main(final String[] args) {
        final List<Stone> stones = new ArrayList<>();
        stones.add(new NormalStone());
        stones.add(new SpecialStone());

        for (final Stone stone : stones) {
            System.out.println(stone.getValue());
        }

    }
}

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