Write down a simple java program that demonstrates the properties of different access modifiers (private, public, and protected) in different classes.
import java.util.*;
class A{
private int a;//this variable only accessed by the methods inside
the object A //it can't be accessed outside of class A
A(int b)//constructor
{
a=b;
}
public void printA()//it can accessed outside of the classA
{
//since printA is the method in classA , it can access varaible
'a'
System.out.println("A:"+a);//printing A value
B b = new B(10);
System.out.println("From A:");//printing B value
b.printB();
}
}
class B
{
protected int b;//it only accessed by the members of classB,other
classes which are in the same package with class B and by
subclasses
B(int c)//constructor
{
b=c;
}
public void printB()//it can accessed outside of the classA
{
//since printB is the method in classB , it can access varaible
'b'
System.out.println("B:"+b);//printing B value
}
}
class C extends B//inherits properties of B
{
C()
{
super(2);
}
//here C is subclass of B
public void printC()
{
System.out.println("From C, B:"+b);//printing B value
}
}
public class Main
{
public static void main(String[] args) {
//testing all classes
A a = new A(1);
a.printA();
B b = new B(2);
b.printB();
C c = new C();
c.printC();
}
}
output:
run:
A:1
From A:
B:10
B:2
From C, B:2
BUILD SUCCESSFUL (total time: 1 second)
//PLS give a thumbs up if you find this helpful, it helps me alot,
thanks.
//if you have any doubts, ask me in the comments
Get Answers For Free
Most questions answered within 1 hours.