9

What is the difference between extends and implements in java with respect to performance and memory,etc. For example take the following scenarios,

1)

public interface PrintResult
{
  public final int NO_ERROR=0;
  public final int SUCCESS=1;
  public final int FAILED=-1;
}


public class PrintProcess implements PrintResult
{
  //Perform some operation
}



2)

public class PrintResult
{
  public final int NO_ERROR=0;
  public final int SUCCESS=1;
  public final int FAILED=-1;
}


public class PrintProcess extends PrintResult
{
  //Perform some operation
}

For above scenarios (1,2) what is difference between using extends (deriving child class), implements (implementing interface). with respect to performance,memory,etc. ?

ApprenticeHacker
  • 21,351
  • 27
  • 103
  • 153
SIVAKUMAR.J
  • 4,258
  • 9
  • 45
  • 80

2 Answers2

8

During a memorable Q&A session, someone asked James Gosling (Java's inventor): If you could do Java over again, what would you change? . I'd leave out classes, he replied

Java does not allow you to extend multiple classes. This avoids some problems related to multiple inheritance. However you can choose to implement multiple interfaces. This is a huge plus.

Some people also believe extends decreases the flexibility of their code.

However, I doubt there is any huge difference in performance, efficiency etc. In fact, they might even produce the same byte-code ( though I'm not sure ). And you are comparing two different things that have different functions, its like asking if Apples are more efficient than Oranges.

ApprenticeHacker
  • 21,351
  • 27
  • 103
  • 153
  • Agrees: its like asking if Apples are more efficient than Oranges. – Haozhun Mar 03 '12 at 13:02
  • Hi, i need more explaination with some real time examples.Then it will helpfull.Because in some articles in internet i notified that both have huge difference with respect to performance.Somtimes in that place which extends suits very well if we use interface then it afects the performance.So please give more explaination – SIVAKUMAR.J Mar 04 '12 at 03:57
  • In practice, it doesn't really matter if they produce the same bytecode. However, bytecode doesn't really matter, because the JIT will easily be smart enough to blow this away. – Kristopher Micinski Jul 30 '12 at 06:19
1

a class extends another class and implements interface. interface extends another interface. Interface hasn't any implemented methods all defined methods are empty so if class inherits from the interface it should implement it's methods. But if Class1 inherits from Class2 then it already have some working methods (from Class2) and just extends Class2.

SomeAnonymousPerson
  • 3,173
  • 1
  • 21
  • 22