Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt interface, abstract class

 
Mani vannan
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
abstract class A
{
public void print();
}
interface B
{
public void print();
}

class C extends A implements B
{
public void print()
{
System.out.println ("Hello world");
}
}

class c extends A and implements B, what version print() method does it impelement? (I mean, print() method of the class 'A' or interface 'B'?)
 
Nibin Jacob Panicker
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hope the u forgot the write the abstract keyword for print() method in class A,otherwise it wont compile.

here,ur extending an abstract class A, so ur expected to override and defive print() method.since ur implementing the interface B also,u have to write code for the print() method declared in interface B.its interesting that both class A and interface B have a print() method with same signature.so to satisfy them u need to define only one print() method like

public void print(){
//some code.
}

in the class C.here both interface and abstract class will be taking the same print() method.
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The point u need to remember is ...

if there are methods with the same name and signature spread across the

interfaces or abstract class that u r extending...

the return type should be same across all the interfaces and the abstract class......


We can overload the methods in the normal way..


Regards

But no idea which of both the print methods is considered???
[ August 26, 2005: Message edited by: A Kumar ]
 
Nibin Jacob Panicker
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hope the following code will give you some idea.

abstract class A{
abstract public void print();
}

interface B {
void print();
}

class C extends A implements B{
public void print(){
System.out.println("Inside Print");
}
}

public class TestClass{
public static void main(String args[]){
A a = new C();
a.print();
B b = new C();
b.print();
}
}

When run, it prints "Inside Print" twice which makes it clear that the print() method in class C satifies both the abstract class and the interface.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic