Reputation: 410
According to the code specified below, b.fun2() is not allowed in main method, I know why it is not working. I wonder that how can I solve these kind of problem. According to the solid programming principle, I need to write an interface for my problem. But this problem prevent me to define an interface.
public interface A{
void fun();
}
public class B implements A{
void fun(){
// some code
}
}
public class C implements A{
void fun(){
// some code
}
void fun2(){
// some code
}
}
public class Main {
public static void main(String[] args){
A b = new C();
b.fun2();
}
}
Upvotes: 0
Views: 104
Reputation: 96
As fun2 is not declared in interface A. You cannot call the fun2 defined in class C using the reference of type A. To call the fun2 using A type reference you have to downcast the reference to child class C. You can tweak this code to call fun2 using reference of type A.
if(b instanceOf C)
((C)b).fun2();
Upvotes: 0
Reputation: 476
General rule here is: using interface reference that is referencing implementing class object you can call only those methods which have been overridden by the implementing class.
To make your code work do:
C c = new C();
c.fun2();
A b=c;
PS: Another problem here is, By default all members of interface are public. so when overriding fun() in classes B and C, the visibility of this method is getting reduced to default level from public; this action is not valid in Java. Use public access specifier whenever overriding interface methods.
Upvotes: 2
Reputation: 7591
You don't have fun2 in A so you can't call to it by using object which reference type is A. To fix this put fun2 abstract method in A interface.
Upvotes: 1
Reputation: 1
Define fun2() in the interface A, but override it in your implementing classes.
public interface A {
void fun();
void fun2();
}
public class C implements A{
void fun(){
// implementation code
}
void fun2(){
// implementation code
}
}
Upvotes: -1
Reputation: 14999
Well fun2
is not part of the interface - you're assigning to an A
which does not have that method. You can do
C b = new C();
then you can call fun2
on that.
Or add fun2
to the interface:
interface A {
void fun();
void fun2();
}
Or extend the interface to keep A
itself unchanged:
interface A2 extends A {
void fun2();
}
class C implements A2 {
}
A2 b = new C();
b.fun2();
Upvotes: 0
Reputation: 84
To be able to access the method fun2
from the class C
you should make a cast to the class C
, like this: ((C) b).fun2();
instead of b.fun2();
It is always reasonable to test whether or not your object is an instance of the class C before making the cast, this way not generating any error. An example:
if(b instanceof C) {
((C) b).fun2();
}
Upvotes: 0