Reputation: 33
The code snippet is as follows:
interface Demo {
void incrementCount();
int getCount();
}
class ChildDemo implements Demo {
public int count = 10;
private void incrementCount() {
count++;
}
public int getCount(){
return count;
}
public static void main(String[] args){
int res;
Demo ob= new ChildDemo ();
res = ob.getCount();
System.out.println(res);
}
}
And, the output whhich I get is as follows:
Compilation Error:incrementCount() in ChildDemo cannot implement incrementCount() in Demo; attempting to assign weaker access privileges to the method.
I would like to clarify a few things:
1. Why is it an error? What is attempting to assign weaker access privileges?
2. Changing it to private
- can the method incrementCount()
can still perform its calculations?
3. What changes should be made to get the output as
10
4. What changes should be made to made to get the output as:
11
Thanks in advance.
Upvotes: 1
Views: 266
Reputation: 7804
All the methods declared in an interface are by default public and abstract. So you need to define these methods in the implementing class or you must declare the class as abstract.
You must understand the rules for overriding methods to get rid of this error. One of the rule says that overridden methods cannot have weaker access specifier. So you cannot make a public methods as private or protected in the overridden method. Make your Child class overridden method public and your code should work fine.
Upvotes: 1
Reputation: 10563
methods declared inside interface are by implicitly public
and all varibales declared in the interface are implicity public static final(constants).
But, you are using private
access
private void incrementCount(){
count++;
}
So the fix would be to add the public
keyword to the method
public void incrementCount(){
count++;
}
Upvotes: 1
Reputation: 122006
Because you are restricting the method access to private
.
All methods in an interface are implicitly public, regardless if you declare it explicitly or not.
http://docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html
The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.
Upvotes: 1
Reputation: 13821
One thing is that it is not allowed, per specifiction, but if you could give the method private
access, then it is would no longer be visible, hence breaking the contract of the interface. In your example, you're never calling incrementCount()
, so the value of your count
variable will stay 10
.
Upvotes: 1