Lab Sheet 10: Access Modifiers, Classes, and Objects in Java


Task 1: Understanding Access Modifiers
Create a Java class called
AccessDemo
With the following:One default access variable
One public variable
One protected variable
One private variable
Methods to demonstrate access to each variable (some accessible, some not)
Create a second class
AccessTester
in:The same package as
AccessDemo
A different package from
AccessDemo
In
AccessTester
, try to access each variable fromAccessDemo
and document which accesses work and which don't, explaining why based on their access modifiers.
Task 2: Creating a Simple Class
Create a class called
BankAccount
with:Private instance variables:
accountNumber
(String),balance
(double),accountHolderName
(String)Public methods:
deposit()
,withdraw()
,checkBalance()
A constructor that initializes the account details
Test your class by:
Creating two BankAccount objects with different initial values
Performing deposit and withdrawal operations
Checking balances after each operation
Task 3: Instance vs Class Variables
Create a class called
Student
with:Instance variables:
studentID
,name
,grade
A class variable:
totalStudents
(to keep track of how many Student objects have been created)Appropriate methods to get and set these values
Test your class by:
Creating 3 Student objects
Printing the value of
totalStudents
after each creationDemonstrating that each object maintains its own instance variables
Task 4: Object References
Create a class called
Book
with:Instance variables:
title
,author
,price
Methods to display book information
Demonstrate object references by:
Creating one Book object
Creating two references to the same Book object
Modifying the book through one reference and showing the change is visible through the other reference
Then creating a new Book object and assigning one reference to it
Task 5: Protected Access Modifier
Create a base class
Vehicle
with:Protected variables:
make
,model
Public method:
displayInfo()
Create a derived class
Car
that extendsVehicle
with:Additional private variable:
numDoors
Method to display all information (including inherited protected variables)
Test your classes by:
Creating a Vehicle object and trying to access its protected members directly
Creating a Car object and showing it can access the protected members of Vehicle
Subscribe to my newsletter
Read articles from Arzath Areeff directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Arzath Areeff
Arzath Areeff
I co-founded digizen.lk to promote online safety and critical thinking. Currently, I’m developing an AI app to fight misinformation. As Founder and CEO of ideaGeek.net, I help turn startup dreams into reality, and I share tech insights and travel stories on my YouTube channels, TechNomad and Rz Omar.