0
0
Javaprogramming~15 mins

Protected access modifier in Java - Mini Project: Build & Apply

Choose your learning style8 modes available
folder_codeUnderstanding the Protected Access Modifier in Java
📖 Scenario: Imagine you are creating a simple program with two classes: a parent class and a child class. You want to share some information between these classes but keep it hidden from other unrelated classes.
🎯 Goal: Build a Java program that shows how the protected access modifier allows a child class to access a variable from its parent class, but keeps it hidden from other classes.
📋 What You'll Learn
Create a parent class called Parent with a protected integer variable named number set to 10.
Create a child class called Child that extends Parent.
In the Child class, write a method called showNumber that returns the value of number.
Create a separate class called Main with a main method to create an object of Child and print the value returned by showNumber.
💡 Why This Matters
🌍 Real World
In real software, <code>protected</code> helps keep important data safe but still accessible to related parts of the program.
💼 Career
Understanding access modifiers like <code>protected</code> is essential for writing secure and well-structured Java code in professional development.
Progress0 / 4 steps
1
Create the Parent class with a protected variable
Create a class called Parent with a protected integer variable named number and set it to 10.
Java
💡 Need a hint?

Use the keyword protected before the variable type to allow child classes to access it.

2
Create the Child class that extends Parent
Create a class called Child that extends the Parent class.
Java
💡 Need a hint?

Use the keyword extends to make Child inherit from Parent.

3
Add a method in Child to access the protected variable
In the Child class, add a method called showNumber that returns the value of the protected variable number.
Java
💡 Need a hint?

Since number is protected, you can access it directly inside Child.

4
Create Main class to test access to protected variable
Create a class called Main with a main method. Inside main, create an object of Child and print the value returned by showNumber.
Java
💡 Need a hint?

Use System.out.println to print the value returned by showNumber.