Understanding Inheritance with default accessibility Modifier in Java
Understanding inheritance with public access specifier in Java
Public accessibility modifier rules are same for instance methods and instance variables.
packageA
├── ClientClassAInSamePackage.java
├── SubClassAInSamePackage.java
├── subPackageA
│ ├── ClientClassAinSameSubPackage.java
│ └── SubClassAinSameSubPackage.java
└── SuperClassA.java
packageB
├── ClientClassBInDifferentPackage.java
├── SubClassBInDifferentPackage.java
└── subPackageB
├── ClientClassBInDifferentSubPackage.java
└── SubClassBInDifferentSubPackage.java
Is SuperClassA Accessible :
[addToAppearHere]
ChildClass extends from the SuperClass SubClassAInSamePackage Example :
package com.big.data.java.packageA;
public class SubClassAInSamePackage extends SuperClassA {
private int subClassAState = 20;
//getPrivateState() private method is not visible
@Override
public String getPublicState() {
return "SubClassAInSamePackage value is " + subClassAState;
}
@Override
protected String getProtectedState() {
return "SubClassAInSamePackage value is " + subClassAState;
}
@Override
String getDefaultState() { return "SubClassAInSamePackage value is " + subClassAState; }
public static void main(String[] args) {
// parent refrence pointing to the child class , SuperClassA and SubClassA are in same package
SuperClassA superVar = new SubClassAInSamePackage();
System.out.println("Parent class method call output for Public is : " + superVar.getPublicState());
System.out.println("Parent class method call output for Protected is : " + superVar.getProtectedState());
System.out.println("Parent class method call output for Private is : " + superVar.getDefaultState());
// Child refrence pointing to its own object
SubClassAInSamePackage child = (SubClassAInSamePackage) superVar;
System.out.println("Child class method call output for Public is " + child.getPublicState());
System.out.println("Child class method call output for Protected is " + child.getProtectedState());
System.out.println("Child class method call output for Private is " + child.getDefaultState());
}
}
[addToAppearHere]
Client Class : uses the reference and object of the SuperClass Example :
package com.big.data.java.packageA;
public class ClientClassAInSamePackage {
public static void main(String[] args) {
// accessing superClassA from a client class in the same package as that of the superClass
SuperClassA superClassA = new SuperClassA();
// Private is not accessible.
System.out.println("Parent class method call output for Public is : " + superClassA.getPublicState());
System.out.println("Parent class method call output for Protected is : " + superClassA.getProtectedState());
System.out.println("Parent class method call output for Default is : " + superClassA.getDefaultState());
//superClassA.getPrivateState() getPrivateState() private method is not visible
}
}