PDA

View Full Version : confused about access privileges while implementing method from interface


vysh
04-24-2009, 04:19 PM
Hi all,

I have declared a method in an interface and implementing it in a class. I havent given any access modifier in the interface and also in the class in which i have implemented which means that it has package access. But I am getting access privilege error.

My code is as follows:

interface DeclareStuff
{
public static final int EASY = 3;
void doStuff(int t);
}
public class TestDeclare implements DeclareStuff
{
public static void main(String [] args)
{
int x = 5;
new TestDeclare().doStuff(++x);
}
void doStuff(int s)
{
s += EASY + ++s;
System.out.println("s " + s);
}
}

And the error which i am getting is:

doStuff(int) in TestDeclare cannot implement doStuff(int) in DeclareStuff; attempting to assign weaker access privileges; was public

shyam
04-26-2009, 05:19 PM
methods declared in an interface are always public. even if you did not specify access

vysh
04-27-2009, 10:19 AM
Ya thats correct. So methods are always public which means that the method 'doStuff' in both the interface and the class are public. So why am i getting the access privilege error?

TheShaner
04-27-2009, 10:23 PM
When you do not use a modifier for a method in a class, it defaults to package-private, which is a weaker access privilege than public. A method in a class that is implementing an interface method must use the public modifier.

In short, put public in front of your doStuff method inside your TestDeclare class.

-Shane

vysh
04-28-2009, 07:42 AM
Shane,

Thank you very much for that. So in precise, a method in an interface by default will have public access, and a method in a class by default will have package access.

I have another related question. Does protected have more privilege or less privilege than default. I am posting a code here which confuses me a little.

class One {
void foo() { }
}
class Two extends One {
protected void foo() { }
public static void main(String args[])
{
}
}


The above code does not give out any error. I am confused whether protected has less or more privilege than its parent class constructor which has default(package) access

TheShaner
04-28-2009, 01:46 PM
Protected has more access than package-private.

Please view Sun's Java tutorial on access control here:
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html

-Shane

vysh
04-29-2009, 11:22 AM
Shane,

Thank you!!!:)