I have an interface here named IFish
. I want to derive it with an abstract class (WalkingFishCommon
) which provides an incomplete implementation, so that classes derived from WalkingFishCommon
do not have to implement the CanWalk
property:
interface IFish { bool Swim(); bool CanWalk { get; } } abstract class WalkingFishCommon : IFish { bool IFish.CanWalk { get { return true; } } // (1) Error: must declare a body, because it is not marked // abstract, extern, or partial // bool IFish.Swim(); // (2) Error: the modifier 'abstract' is not valid for this item // abstract bool IFish.Swim(); // (3): If no declaration is provided, compiler says // "WalkingFishCommon does not implement member IFish.Swim()" // {no declaration} // (4) Error: the modifier 'virtual' is not valid for this item // virtual bool IFish.Swim(); // (5) Compiles, but fails to force derived class to implement Swim() bool IFish.Swim() { return true; } }
I've not yet discovered how to make the compiler happy, while still achieving the goal of forcing classes derived from WalkingFishCommon to implement the Swim()
method. Particularly baffling is the delta between (1) and (2), where the compiler alternates between complaining that Swim()
isn't marked abstract, and in the next breath complains that it can't be marked abstract. Interesting error!
Any help?
You can do this by creating an abstract class that implements the interface. Any sub-class of this abstract class will be required to implement any interface methods that were not yet defined. See: Java tutorial on abstract classes.
1) Abstract method has no body. 2) Always end the declaration with a semicolon(;). 3) It must be overridden. An abstract class must be extended and in a same way abstract method must be overridden.
Java Abstract class can implement interfaces without even providing the implementation of interface methods. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation. We can run abstract class in java like any other class if it has main() method.
And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it. Hence, if you want to prevent instantiation of a class directly you can declare it abstract.
Just declare Swim
as abstract
and don't try to use explicit interface declaration for it (i.e. remove IFish
).
abstract class WalkingFishCommon : IFish { public bool CanWalk { get { return true; } } public abstract bool Swim(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With