+ 1
Java - Access Modifiers
I'm a little confused with the access modifiers 'default' and 'protected'. Can anybody explain it a little broader?
5 Antworten
+ 2
A protected member within a class means that it can only be accessed from within that same class or from the derived class, and no where else.
For example, if you have the class 'foods' which has a protected int named 'colour', and it also has a class that derives from it named 'potato'. 'colour', in this case, can only be accessed from within the food class and the potato class, and no where else. Trying it access it from a separate class will result in an error.
The default access modifier is similar to the public access modifier, except it can only be accessed by classes within the same package.
I hope this helped d:
+ 2
public class Program
{
public static void main(String[] args) {
Country c = new Country();
c.name = "France";
c.capital = "Paris";
System.out.println("Country: " + c.name);
System.out.println("Capital: " + c.capital);
}
}
class Country{
//change the code bellow
public String name;
public String capital;
}
+ 1
To add on, in Java you have a few ways to organize your code. Packages are one of the ways. They're a collection of several (usually related) classes. The default access modifier makes members accessible from within the class and classes that are in the same package, whereas protected makes members accessible only from within the class and it's derived classes.
So protected is like private, but allows access from derived classes. And default is like public, but restricts access to classes that share the same package.
+ 1
i cant really find the difference between default and public usage
+ 1
Java - Access Modifiers
public class Program
{
public static void main(String[] args) {
Country c = new Country();
c.name = "France";
c.capital = "Paris";
System.out.println("Country: " + c.name);
System.out.println("Capital: " + c.capital);
}
}
public class Country{
//change the code below
protected String name;
protected String capital;
}