• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Interface implement

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
Here is the question, and I have the question on its answer.
Given the following definition, which deficitions are valid?
interface I{
void setValue(int val);
int getValue();
}
Select all valid answers.
A) class A extends I{
int value;
void setValue(int val){value=val;}
int getValue(){ return value;}
}
B) interface B extend I{
void increment();}
C) abstract class C implements I {
int getValue(){ return 0;}
abstract void increment();}
D) interface D implements I{
void increment();}
E) class E implements I{
int value;
public void setValue(int val){ value=val;}
}
the right answer is b.
Although I know classes can not extend interface and they must implement them. interface can extend other interface. So the answer A & D are wrong. How to explain choice C and E? why they are wrong?
Thanks
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, Class E says it implements interface I, but then it lies!!!

Since E says it is going to implement I, it needs to provide implementations for ALL of I's member functions. I contains TWO methods, getValue() and setValue(), but here E is only implementing setValue(). Where is getValue()? Since E doesn't implement it, it should decalare that is an abstract class:
abstract class E implements I...
Item C is a little more sneaky. JLS 9.1.4 states:

All interface members are implicitly public.


So when class C implements getValue()...

It is trying to implement getValue() with weaker access priviledges (default access VS public access) so this is a compiler error.
Rob
 
Angela Xia
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you so much and it really helps.
 
I brought this back from the farm where they grow the tiny ads:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic