Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and Interface

I've been trying to understand inheritance when interfaces are involved. I want to know how the subclasses are created if they follow the following:

For Example, let's say i have:

  1. a Superclass which implements an Interface I
  2. and couple of subclasses which extend the superclass A

My Questions

  1. Do i have to provide the implementation of the interface methods 'q and r' in all of the subclasses which extend A?

  2. If i don't provide the implementation of the interface in a subclass will i have to make that subclass an Abstract Class?

  3. Is it possible for any of the subclass to implement I? e.g. Class C extends A implements I, is this possible? even though it's already extending a superclass which implements I?

  4. Let's say i don't provide the implementation of method r from the interface I, then i will have to make the superclass A and Abstract class! is that correct?

My example code:

    //superclass
    public class A implements I{
    x(){System.out.println("superclass x");}
    y(){System.out.println("superclass y");}
    q(){System.out.println("interface method q");}
    r(){System.out.println("interface method r");}
    }

    //Interface
    public Interface I{
    public void q();
    public void r();
    }

    //subclass 1
    public class B extends A{
    //will i have to implement the method q and r?
    x(){System.out.println("called method x in B");}
    y(){System.out.println("called method y in B");}
    }

    //subclass 2
    public class C extends A{
    //will i have to implement the method q and r?
    x(){System.out.println("called method x in C");}
    y(){System.out.println("called method y in C");}
}
like image 734
Jon Snow Avatar asked Oct 30 '12 00:10

Jon Snow


1 Answers

1) No, you do not need to implement the methods in the subclasses, because they are already defined in the superclass. The subclass will inherit those method definitons.

2) No, see 1. The only exception is if the superclass is abstract and doesn't implement the interface, then you will need to implement it in the subclass if the subclass is not abstract.

3) No. It might compile properly, but will have no effect, and so shouldn't be done.

4) Yes, this is correct. If you do not implement a method from the interface, you need to make the class abstract.

like image 180
Jonathon Ashworth Avatar answered Sep 21 '22 03:09

Jonathon Ashworth