0

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() {
     ...
     ..
    }
} 
Bulbasaur
  • 696
  • 1
  • 14
  • 22

4 Answers4

1

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

Bruce
  • 8,609
  • 8
  • 54
  • 83
  • @OliverCharlesworth [says otherwise...](http://stackoverflow.com/questions/14132285/java-methods-override-vs-abstract#comment19566511_14132285) It may just dependent on the version of Java. This may not work in version 1.5. – Mr. Polywhirl Dec 19 '14 at 11:33
  • There was a typo in my code earlier, check it out now – Bulbasaur Dec 19 '14 at 11:52
  • 1
    you put weaker access modifier in your sub class did you check that – Bruce Dec 19 '14 at 12:03
0

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

Roman Kazanovskyi
  • 3,370
  • 1
  • 21
  • 22
  • This is what I did, it doesn't work. It says: : method does not override or implement a method from a supertype(after adding override annotation) – Bulbasaur Dec 19 '14 at 11:56
0

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());
    }
}
0

If you could access the grandparent directly you would create a dependency on the implementation of the father, and this would violate encapsulation.

Tal
  • 11
  • 4