Here in this article, we are going to study why we are not allowed to use these keywords while declaring outer classes. But before understating the reason behind this we need to understand Java access specifiers and their use cases. There is total 4 access specifier in Java mentioned below in the order of their accessibility.
- private: anything (field, class, method, interface etc.) defined using private keyword is only accessible inside the entity (class or package or interface) in which it is defined.
- default: only accessible inside the same package and it is also known as package-private (No modifiers needed).
- protected: only accessible inside the same package plus outside the package within child classes through inheritance only.
- public: can be accessed from anywhere.
Why an outer class can not be private
As we already know a field defined in a class using private keyword can only be accessible within the same class and is not visible to outside world.So what will happen if we will define a class private, that class will only be accessible within the entity in which it is defined which in our case is its package?
Let’s consider below example of class A
package com.example;
class A {
private int a = 10;
// We can access a private field by creating object of same class inside the same class
// But realy no body creates object of a class inside the same class
public void usePrivateField(){
A objA = new A();
System.out.println(objA.a);
}
}
Field ‘a’ is declared as private inside ‘A’ class and because of it ‘a’ field becomes private to class ‘A' and can only be accessed within ‘A’. Now let’s assume we are allowed to declare class ‘A’ as private, so in this case class ‘A’ will become private to package ‘com.example’ and will not be accessible from outside of the package.
So defining private access to the class will make it accessible inside the same package which default keyword already do for us, Therefore there is no benefit of defining a class private it will only make things ambiguous.
Why an outer class can not be protected
Access specifier protected is sometimes got confused with the default keyword, for some programmers it becomes hard to identify the exact difference between default and protected accesses. But it is very clear as mentioned belowdefault → only accessible within the same package.
protected → accessible within the same package as well as outside of the package in child classes through inheritance only.
Let’s consider below example of class A
package com.example;
public class A {
protected int a = 10;
}
And suppose there is one more class in another package
package com.experiment;
public class B extends A {
// Outside of the package protected field can be accessed through inheritance
public void printUsingInheritance() {
System.out.println(a);
}
// In child class we can access protected field through instantiation of child class
// But should we do that ? .... No
public void printUsingInstantiation() {
B b = new B();
System.out.println(b.a);
// But not through instantiation of the class which contains the protected field
A a = new A();
System.out.println(a.a); // Compilation error “The field A.a is not visible”
}
}
And suppose there is one more class in the same package
package com.experiment;
public class C {
// We can not access protected field outside of the child class through instantiation
public void printUsingInstantiation() {
B b = new B();
System.out.println(b.a); // Compilation error “The field B.a is not visible”
}
}
And if same class 'C' extends 'B', Then again we will be able to access 'a' the same way we are able to access it in B class
package com.experiment;
public class C extends B {
// outside of the package protected field can only be accessed through inheritance
public void printUsingInheritance() {
System.out.println(a);
}
// In child class we can access protected field through instantiation as well
public void printUsingInstantiation() {
C c = new C();
System.out.println(c.a);
}
}
Because ‘a’ field is protected, we can access it in any way we want to inside the package but outside of the package ‘com.example’ it is only accessible through inheritance and because class ‘B’ is extending class ‘A’ we can use field ‘a’ inside class ‘B’ only as we are doing in printUsingInheritance() method. And we can not use ‘a’ outside of class ‘B’ without inheriting 'B' in another class.
Field ‘a’ will be accessible inside class B in through inheritance only but if we try to create an instance of class ‘B’ in ‘B’ class and then try to access ‘a’ from that instance we will able to use it in a similar manner we can use a private variable in the same class by instantiation of same class.
So If we are allowed to make a class protected then we can access it inside the package very easily but for accessing that class outside of the package we first need to extend that entity in which this class is defined which is again is its package.
And since a package can not be extended (can be imported) defining a class protected will again make it similar to defining it as default which we can already do. So again there is no benefit of defining a class protected.
Please feel free to reach me if you face any problem in understanding it or found any problem in the article.
Great Blog
ReplyDeletethanks buddy
DeleteSorry Jorge, It was a mistake, I have updated the article.
ReplyDeleteWe can access it within the same class through instantiation as well but not outside of the class.
Since class A is public it doesn't matter which modifier you give to members inside class A. Class A is visible to everyone
ReplyDeleteDefinitely if `A` is public, it will be accessible from everywhere but if we are allowed to make it protected or private because as discussed, it does make any sense.
ReplyDeleteTy for explaining so well!!🙂it's really helped...!!one doubt..since parent class object is also the object of child class so when u tri to access the parent class memeber a using parent class object a in its child class...as a.a y it's saying not visible ....but when child class object u created and accessed b.a ,it's compiled well...y!!(through inheritance parent class object is also the object of child class naa??!!)PLZZ clarify 🙂😐
ReplyDeleteIts because if we try to access a protected member outside of the package, it can accessed in the child class only and that is too using the inheritance only. Which means class `B` will have access to `a` because it inherited the same field from its parent `A` but if we try to make object of `A` and then try to access `a` from it, field `a` will not visible.
Deletethat was a great explanation
ReplyDeleteThanks Mohit
Deleteinterface never be private and methods of interface never be final or private.please change in private modifier.
ReplyDelete@Ashish I am not able to understand what are you trying to say, but I have not mentioned it anywhere that we can declare a private outer interface or its method can be final (we can declare a private inner interface).
DeleteA very good article! With a simple code you have managed to extract some key feature. Thanks!
ReplyDeleteThanks!
DeleteThanks
ReplyDeletewhy can't we make "protected class A " and use it within the same package in another class by creating the object of the class A?
ReplyDeleteprotected class A{
int a = 10;
}
class B{
public static void main(String args[])
{
A o = new A();
System.out.println(o.a);
}
}
Antalya
ReplyDeleteAntep
Burdur
Sakarya
istanbul
NİHO0
Batman
ReplyDeleteArdahan
Adıyaman
Antalya
Giresun
F1V
Muğla
ReplyDeleteSamsun
Eskişehir
Sakarya
Kars
JS4P
C7C37
ReplyDeleteTekirdağ Fayans Ustası
Adana Evden Eve Nakliyat
Batman Evden Eve Nakliyat
Trabzon Evden Eve Nakliyat
Tekirdağ Cam Balkon
7A0FA
ReplyDeleteMardin Parça Eşya Taşıma
Düzce Evden Eve Nakliyat
Hatay Şehirler Arası Nakliyat
Uşak Parça Eşya Taşıma
Binance Güvenilir mi
Manisa Lojistik
Sakarya Parça Eşya Taşıma
Sakarya Lojistik
Ünye Halı Yıkama
F7FC9
ReplyDeleteAnkara Parke Ustası
Niğde Parça Eşya Taşıma
Ardahan Evden Eve Nakliyat
Lunc Coin Hangi Borsada
Ünye Parke Ustası
Zonguldak Parça Eşya Taşıma
İstanbul Lojistik
Trabzon Evden Eve Nakliyat
Yozgat Şehir İçi Nakliyat
CC7F4
ReplyDeleteÇorum Evden Eve Nakliyat
Kütahya Evden Eve Nakliyat
Artvin Evden Eve Nakliyat
Ünye Televizyon Tamircisi
İstanbul Şehirler Arası Nakliyat
Sinop Şehirler Arası Nakliyat
Bitmex Güvenilir mi
Çerkezköy Çamaşır Makinesi Tamircisi
Hakkari Şehirler Arası Nakliyat
1BEC5
ReplyDeleteBayburt Lojistik
Bitrue Güvenilir mi
Zonguldak Şehirler Arası Nakliyat
Gölbaşı Parke Ustası
Şırnak Lojistik
Ardahan Şehir İçi Nakliyat
Bolu Evden Eve Nakliyat
Muğla Lojistik
Sivas Evden Eve Nakliyat
AEA35
ReplyDeleteBingöl Evden Eve Nakliyat
Amasya Lojistik
Gölbaşı Parke Ustası
Clysterum Coin Hangi Borsada
Etlik Parke Ustası
Çanakkale Evden Eve Nakliyat
Pancakeswap Güvenilir mi
Antalya Lojistik
Siirt Evden Eve Nakliyat
4E08C
ReplyDeleteAntalya Sohbet Chat
kadınlarla sohbet et
Niğde Telefonda Rastgele Sohbet
diyarbakır görüntülü sohbet yabancı
en iyi görüntülü sohbet uygulamaları
Eskişehir Sesli Sohbet Odası
edirne en iyi ücretsiz sohbet siteleri
bilecik nanytoo sohbet
sivas görüntülü sohbet ücretsiz
01073
ReplyDeletegörüntülü sohbet sitesi
gümüşhane canlı ücretsiz sohbet
rastgele sohbet
sohbet uygulamaları
şırnak yabancı sohbet
adıyaman sesli sohbet
istanbul canli sohbet
Karaman Rastgele Sohbet Siteleri
kadınlarla görüntülü sohbet
8669D
ReplyDeletecanli sohbet
kaldıraç nasıl yapılır
coin nasıl alınır
kripto para haram mı
probit
bitcoin ne zaman çıktı
kripto para nasıl alınır
binance
bitcoin nasıl kazanılır
70ABE
ReplyDeletebitget
4g mobil
kraken
coinex
canlı sohbet ücretsiz
kraken
mexc
kripto para nereden alınır
probit
4F2C8
ReplyDelete----
----
----
matadorbet
----
----
----
----
----
97CDC
ReplyDeletegüvenilir canlı show
A9DE2
ReplyDeletecanlı güvenilir şov
C68F405374
ReplyDeletebayan azdırıcı damla
sildegra
geciktirici
bufalo içecek
viga
sertleştirici
lay era
sinegra
viagra
48E466AC26
ReplyDeleteviagra
performans arttırıcı
sertleştirici
lifta
sildegra
sinegra
bayan azdırıcı damla
cobra vega
lady era
B050108895
ReplyDeletevigrande
ücretli şov
stag
cam şov
kaldırıcı
sildegra
sinegra
whatsapp görüntülü show güvenilir
lifta
57A29A28D5
ReplyDeletekaldırıcı
green temptation
telegram görüntülü şov
skype şov
görüntülü şov whatsapp numarası
vega
bayan azdırıcı damla
geciktirici
delay
1C96E06C24
ReplyDeletegörüntülü şov
sinegra 100 mg
canli cam show
kaldırıcı hap
vega
görüntülü şov whatsapp numarası
geciktirici jel
themra macun
cam show
3C1E22F171
ReplyDeleteyapay kızlık zarı
vega
görüntülü show
whatsapp görüntülü şov
green temptation
canli cam show
lady era hap
sinegra 100 mg
skype şov