Access Modifiers:
public – accessible within the class, within the same
package and outside the package.
protected – accessible within the class, within the same
package. It is accessible outside the package, but only to the class that is a
subclass. Also it will be accessible only on the object of child, still not
accessible on the object of Parent.
default - accessible
within the same class and within the same package. Not accessible outside the
package.
private – accessible only within the same class.
Let us review these access modifier by taking and
example of ATM.
We will make 2 packages with atleast 1 class in each
of them.
package mybank.atm;
public class Atm
{
public
String bankName;
public
String location;
String
policeContactNo;
private cashInAtm;
public float
withdrawMoney(String cardNo)
{
// anybody should be able to withdraw money
}
protected void
getDaysTransaction(String cardNo)
{
// should be available t
}
private getTotalCashInAtm()
{
//
no one needs to know what is the total cash in ATM
}
void
callPolice()
{
// bank can make an automated
call to police if somebody tries to vandalize the ATM
// the security guard can also
make a call to police if suspects any robbery at ATM
}
}
package mybank.customer;
public class Customer
{
public
String customerName;
public
static void main(String args[])
{
Atm atm = new Atm();
atm.withdrawMoney(“”);
atm.callPolice(); // will give
compilation error
atm.getTotalCashInAtm(); // will give compilation error
}
}
package mybank.atm;
public class SecurityGuard
{
public
String guardName;
public
static void main(String args[])
{
Atm atm = new Atm();
atm.withdrawMoney();
atm.callPolice();
atm.getTotalCashInAtm(); // will give compilation error
}
}
No comments:
Post a Comment