+ 1

Java - Access Modifiers

I'm a little confused with the access modifiers 'default' and 'protected'. Can anybody explain it a little broader?

16th Jan 2018, 4:26 AM
Rubel Chowdhury
5 Respostas
+ 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:
16th Jan 2018, 5:13 AM
Faisal
Faisal - avatar
+ 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; }
7th Jan 2022, 2:31 PM
Srinivas vedullapalli
Srinivas vedullapalli - avatar
+ 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.
21st Jan 2018, 9:44 PM
Jiren The Grey
Jiren The Grey - avatar
+ 1
i cant really find the difference between default and public usage
15th Feb 2018, 5:38 PM
raghu kittu
raghu kittu - avatar
+ 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; }
28th May 2023, 6:11 PM
Kawinphop Chomnikorn