I have an abstract class A, and an abstract class B inheriting A.
Then, I have a class C(not abstract) that inherits B.
I need to override some methods declared abstract in A, and not implemented in B to be implemented in C.
But when I try to do this, and add an Override annotation on top of my method, it says its not valid as that method does not exist in the parent.
How can I do this?
Code with signatures:
public abstract class A {
abstract protected EntityType getEntityType();
abstract protected ActionResponse doProcessing();
}
public abstract class B extends A {
#Override
EntityType getEntityType() {
....
...
}
}
public class C extends B {
#Override
ActionResponse doProcessing() {
...
..
}
}
Access Modifier of the Sub class can't weaker than it's Super Class. It is better to change the Access Modifier of the sub classes to protected from default
A:
public abstract class A {
public abstract D getClassD();
}
B:
public abstract class B extends A{
}
D:
public class D {
}
And C:
public class C extends B {
D d = new D();
#Override
public D getClassD() {
return this.d;
}
}
It's correct. You cannot create class C without override method getClassD().
Please add field and initialize it.
If you use Eclipse you can change in setting that IDE should put #Override or not
Your scenario works just fine in JavaSE 1.7. What version of java are you using?
public abstract class A {
protected abstract Integer getMyInt();
protected abstract String getMyString();
}
public abstract class B extends A {
#Override
protected String getMyString(){
return "The answer is";
}
}
public class C extends B {
#Override
protected Integer getMyInt() {
return 42;
}
}
public class Test {
public static void main(String[] args) {
C c = new C();
System.out.println(c.getMyString() + " " + c.getMyInt());
}
}
If you could access the grandparent directly you would create a dependency on the implementation of the father, and this would violate encapsulation.
Related
In java, i can do this:
public class A {
//...
}
public class B extends A {
//...
}
public interface I {
void test(A a);
}
public class C implements I {
//i can use class B as parameters in java but how to do in .net ?
// not work in .net
#override
public void test(B b){
}
}
I can use class B as parameters in java but how to do in .net ?
In order to implement the interface member I.test(A a), the the test() method of the C must be public, non-static, and have the same name and signature as the interface member.
C.test fails one criterion: it does not have the same signature as I.test.
Option 1: Implement the Interface
public class A {
//...
}
public class B extends A {
//...
}
public interface I {
void test(A a);
}
public class C implements I {
public void test(A a){
}
}
of course you can still pass B instances into C.test:
var b = new B();
var c = new C();
c.test(b);//works just fine
Option 2: Change the Interface
Say your implementation of I in C depends on a property present on B but not on A. Suppose further that it makes sense that I.test is a perfectly valid method to write so long as the parameter being passed in extends A.
In that scenario, you can try something like this:
public class A
{
//...
}
public class B : A
{
//...
}
public interface I<T> where T : A
{
void test(T a);
}
public class C : I<B>
{
public void test(B b)
{
}
}
Which utilizes generics as well as generic type constraints and seems like it may be a little closer to what you are trying to represent/accomplish.
I have two abstract generic classes. They cooperate and hence depend on each other. Occasionally one needs to pass this to the other. I am trying to find a type safe way to do this:
public abstract class AbstractA<T extends AbstractB<? extends AbstractA<T>>> {
protected void foo() {
T aB = createB();
aB.setA(this);
}
/** factory method */
abstract public T createB();
}
public abstract class AbstractB<T extends AbstractA<? extends AbstractB<T>>> {
private T theA;
#SuppressWarnings("unchecked")
public void setA(AbstractA<? extends AbstractB<?>> theA) { // dreamed of parameter list (T theA)
// Unchecked cast from AbstractA<capture#1-of ? extends AbstractB<?>> to T
this.theA = (T) theA;
}
protected T getA() {
return theA;
}
}
My question is whether I can find a cleaner way so I avoid the unchecked cast in AbstractB.setA(). I had hoped to declare it setA(T theA), but then the call to it won’t compile: The method setA(capture#1-of ? extends AbstractA<T>) in the type AbstractB<capture#1-of ? extends AbstractA<T>> is not applicable for the arguments (AbstractA<T>). I am still struggling to understand whether the compiler should know enough to allow it or not.
I was thinking my problem may be related to the one discussed in Java generics compilation error - The method method(Class<capture#1-of ? extends Interface>) in the type <type> is not applicable for the arguments. My unchecked cast was inspired from there. I liked the reply by Tom Hawtin - tackling, but I have not found a way to apply it to my situation.
My user will declare concrete subclasses and instantiate one ConcreteA and any number of ConcreteBs:
public class ConcreteA extends AbstractA<ConcreteB> {
#Override
public ConcreteB createB() {
return new ConcreteB();
}
public void concreteAMethod() {
// ...
}
}
public class ConcreteB extends AbstractB<ConcreteA> {
public void bar() {
ConcreteA a = getA();
a.concreteAMethod();
}
}
(class AbstractA<T extends AbstractB<? extends AbstractA<T>>> looks a bit complicated; I thought I needed it for concrete subclasses to know each other’s exact types, but apparently it doesn’t give me that.)
If I've understood you correctly, this should create the binding you want.
class Demo {
public static void main(String[] args) {
ConcreteA a = new ConcreteA();
ConcreteB b = new ConcreteB();
a.foo(b);
b = (ConcreteB) a.getB();
}
}
abstract class AbstractA<T extends AbstractB<?>>{
private AbstractB<?> b;
public AbstractB<?> getB(){
return b;
}
void foo(AbstractB<?> aB) {
b = aB;
aB.bar(this);
}
}
abstract class AbstractB<T extends AbstractA<?>> {
private AbstractA<?> a;
public AbstractA<?> getA(){
return a;
}
public void bar(AbstractA<?> theA) {
a = theA;
theA.foo(this);
}
}
class ConcreteA extends AbstractA<ConcreteB>{
}
class ConcreteB extends AbstractB<ConcreteA>{
}
I think this is what you ended up at yourself. I am not able to remove the cast to ConcreteB, getB() simply cannot be sure of the type it is holding. I now see why you had multiple generic statements in your declaration. :)
If you're up for it, continue searching, and post your own answer if you find one, I'd love to see it.
I hope solving half your problem counts for anything. ;)
I think I got it now why I cannot declare public void setA(T theA) in AbstractB and then call it as aB.setA(this) in foo(). Suppose we had:
class IntermediateConcreteA extends AbstractA<ConcreteB> {
#Override
public ConcreteB createB() {
return new ConcreteB();
}
}
class SubConcreteA1 extends IntermediateConcreteA {}
class SubConcreteA2 extends IntermediateConcreteA {}
class ConcreteB extends AbstractB<SubConcreteA2> {}
Now if I have a SubConcreteA1 and call its foo(), then createB() will return an object that can pass as an AbstractB<SubConcreteA2> but cannot pass as an AbstractB<SubConcreteA1>. Therefore its setA() shouldn’t accept this as an argument. The compiler error message is logical after all.
Each abstract class would be parameterized with two type parameters, one for the actual concrete class of A, and one for the actual concrete class of B:
public abstract class AbstractA<A extends AbstractA<A,B>, B extends AbstractB<A,B>> {
protected void foo() {
B aB = createB();
aB.setA(getThis());
}
abstract public A getThis();
abstract public B createB();
}
public abstract class AbstractB<A extends AbstractA<A,B>, B extends AbstractB<A,B>> {
private A theA;
public void setA(A theA) {
this.theA = theA;
}
protected A getA() {
return theA;
}
}
public class ConcreteA extends AbstractA<ConcreteA, ConcreteB> {
#Override
public ConcreteA getThis() {
return this;
}
#Override
public ConcreteB createB() {
return new ConcreteB();
}
public void concreteAMethod() {
// ...
}
}
public class ConcreteB extends AbstractB<ConcreteA, ConcreteB> {
public void bar() {
ConcreteA a = getA();
a.concreteAMethod();
}
}
A factory can solve it:
public abstract class AbstractA {
public void abstractAMethod() {
// ...
}
}
public abstract class AbstractB<A> {
private A theA;
public void setA(A theA) {
this.theA = theA;
}
protected A getA() {
return theA;
}
}
public abstract class AbstractFactory<A extends AbstractA, B extends AbstractB<A>> {
private A theA = createA();
public A getA() {
return theA ;
}
public B getNextB() {
B newB = createB();
newB.setA(theA);
return newB;
}
protected abstract A createA();
protected abstract B createB();
}
Now the user can go:
public class ConcreteA extends AbstractA {
public void concreteAMethod() {
// ...
}
}
public class ConcreteB extends AbstractB<ConcreteA> {
public void bar() {
ConcreteA a = getA();
a.abstractAMethod();
a.concreteAMethod();
}
}
public class ConcreteFactory extends AbstractFactory<ConcreteA, ConcreteB> {
#Override
protected ConcreteA createA() {
return new ConcreteA();
}
#Override
protected ConcreteB createB() {
return new ConcreteB();
}
}
I don’t think it’s a typical application of the abstract factory pattern, though …
#Chris Wohlert, I did give up in my production code since I considered the factory overkill, but I could not let go of the theoretical question.
I have come to realize that my problem really came out of stuffing two concepts into the AbstractA/ConcreteA hierarchy that didn’t belong together. Though maybe not interesting to very many, I am posting this insight for two reasons: (1) I feel I owe Chris Wohlert the answer I have found myself (2) more importantly, I’d love to inspire anyone else facing a similar tricky generics issue to review your design from a higher level than just solving the generics and/or class cast issue. It certainly helped me. The cast/generics problem was a sign that something more fundamental was not quite right.
public abstract class AbstractA {
public void foo() {
AbstractB aB = createB();
aB.setA(this);
}
/** factory method */
abstract public AbstractB createB();
}
public abstract class AbstractB {
private AbstractA theA;
public void setA(AbstractA theA) {
this.theA = theA;
}
// methods that use theA
}
No generics and no class cast. Taking out the stuff that didn’t belong in the A class hierarchy into ConcreteC (with no AbstractC):
public class Client {
public void putTheActTogether() {
ConcreteC theC = new ConcreteC();
// the concrete A
AbstractA theA = new AbstractA() {
#Override
public AbstractB createB() {
return new ConcreteB(theC);
}
};
// call methods in theA
}
}
public class ConcreteB extends AbstractB {
private final ConcreteC c;
public ConcreteB(ConcreteC c) {
super();
this.c = c;
}
public void bar() {
c.concreteCMethod();
}
}
public class ConcreteC {
public void concreteCMethod() { // was concreteAMethod(); moved and renamed
// ...
}
}
The client needs a few more lines than before. In my real-world code I needed to duplicate one final field in AbstractA and ConcreteC, but it made sense to do. All in all I consider it a low price for a design that is otherwise pure and simple.
I have created some interface such that:
public interface A{
}
and i would like to call the method a that I have already implemented in class B in interface A such that:
public class B{
public boolean a(){
return true;
}
}
public interface A{
public void call {
a();
}
}
without any errors, any help please?
What you want to do is strictly speaking impossible, as you cannot define method implementations in an interface. You can get something similar by defining an implementation of the interface that extends B. Hopefully that is close enough.
public class AImplementation extends B implements A{
public void call(){
a();
}
}
If you are using any java version before 8, then stick with the answers of #tinker and #Davis Broda. They provide better design since they do not couple your interface to the B class. If you insist however, in java 8 you can have default method implementations as well as static methods in an interface.
If your method is for inheritance then you have to use a default method. Add the default keyword:
default void call() {
...
}
Now the problem is how to get a reference to the class in order to call the method since you cannot have instance fields in interfaces. You have two choices:
Pass the object of B as a method parameter:
public interface A{
default void call(B b) {
b.a();
}
}
or make the method in B static
public interface A{
default void call() {
B.a();
}
}
If your method is not for inheritance but just a utility than you can make it static as :
public interface A{
public static void call() {
B.a();
}
}
I agree with #Davis Broda's answer, there is no way to have a method definition in an interface. But I have another way to address this.
You can have the interface and then have an abstract class implement this interface, and then have all other classes extend the abstract class. The abstract class doesn't have to extend the class from where you want to call the method, you could call it from an instance of that class too.
public interface A {
void caller();
}
public class B {
public void callMe() {
}
}
public class AbstractA implements A {
private B b;
public AbstractA(B b) {
this.b = b;
}
#Override
public void caller() {
b.callMe();
}
}
This way, all implementations of AbstractA will be able to call B's callMe method. And you can access this directly from the interface using this code:
A anInstance = someInstance;
anInstance.caller();
Your question is not very clear, but if I'm guessing right, you want interface A to be kind of a generic caller.
If you're using Java 8, you can achive that using a method reference:
public class B {
public boolean a() {
return true;
}
}
public interface A<T> {
default T call(Supplier<T> s) {
return s.get();
}
}
public class AImpl
implements A<Boolean> {
}
public class Sample {
public static void main(String[] args) {
AImpl a = new AImpl();
B b = new B();
boolean result = a.call(b::a);
System.out.println(result); // true
}
}
This uses Supplier<T> because your method a() in class B returns a boolean and does not receive any arguments.
So suppose I have 2 classes:
public class A
{
public void
f()
{
}
}
public class B
{
public void
f()
{
}
}
I would like to write a generic static method that could call f when passed an instance of A or B. I tried:
public class C
{
public static <T extends A & B> void
g(T t)
{
t.f();
}
public static void main(String[] args)
{
A a = new A();
g(a);
}
}
But the compiler claims A is not a valid substitute for "T extends A & B", which I assume is because T must extend BOTH A and B, which obviously A does not. I could not find a way to specify something like "T extends A OR B". Is something like this not achievable? I am a java neophyte, so any help with this would be appreciated.
You can only specify one generic type. Use interfaces instead.
An interface specifies a certain set of methods, each member of it has to have. A class can implement multiple interfaces.
In your example, I would define an interface with the method f():
public interface MyInterface {
void f();
}
Let A and B implement the interface:
public class A implements MyInterface
{
#Override
public void f() {
// ...
}
}
public class B implements MyInterface
{
#Override
public void f() {
// ...
}
}
Then you can just specify the interface as type of the argument for your method:
public static void g(MyInterface obj)
{
obj.f();
}
For more detail on interfaces, check the Java documentation: What Is an Interface?
I have a class and I would like to create one abstract method for return instance of class byself.For example...
public abstract class A {
.........
public abstract Object getInstance();
}
public class B extends A {
#Override
public Object getInstance() {
return this;
}
}
public class C extends A {
#Override
public Object getInstance() {
return this;
}
}
Above codes , method getInstance() can't force to return instances of child classes B and C. This is my main point to get it. How could I create an abstract method to force for return instance of child classes ?
What you are looking for are generic methods:
public class Q22213940
{
public static void main(String[] args)
{
final B b = new B();
final C c = new C();
System.out.println("b = b.getInstance() " + b == b.getInstance());
System.out.println("c = c.getInstance() " + c == c.getInstance());
}
public static class C extends A
{
#Override
public C getInstance()
{
return this;
}
}
public static class B extends A
{
#Override
public B getInstance()
{
return this;
}
}
public abstract static class A
{
public abstract <T> T getInstance();
}
}
Why? This serves no functional purpose.
Why you want to do this I have no idea, this makes no logical sense, you have to have a reference to the object to begin with to call .getInstance(); which only returns you the same reference you already have.
Why don't you return the Abstract class A itself?
public abstract class A {
.........
public abstract A getInstance();
}
public abstract B getInstance();
Implementing this method in a class will allow any code that IS-A B to return. This a co-variant return, where a return type can be the class type or a sub-class of the class type. So this would include an instance of class C because C IS-A B through inheritance since C extends from B.
So a class could override this method like so:
public class C extends A {
public B getInstance(){
return new C(); // return a C object
}
}
Because A is abstract you can't create an instance of it. The code below will force the subclasses to implement there own implementation.
public abstract class A {
............
public abstract A getInstance();
}