When you start exploring Object-Oriented Programming (OOP), it's important to know about access modifiers. These are special words that control how you can use different parts of your code. The main ones are public, private, and protected. Let’s break them down.
Car
. If it has a public method like startEngine()
, you can call this method from other classes without any problems.public class Car {
public void startEngine() {
System.out.println("Engine started!");
}
}
Car
class has a private property called engineStatus
, you won’t be able to access engineStatus
from any other class. This helps keep data safe.public class Car {
private String engineStatus;
private void checkEngine() {
// Only accessible within Car
}
}
Car
named ElectricCar
, it can use the protected parts of Car
.public class Car {
protected String fuelType;
}
public class ElectricCar extends Car {
public void displayFuelType() {
System.out.println("Fuel Type: " + fuelType);
}
}
Using these keywords wisely helps you decide how much of your class can be used by others. This protects your data and helps create clear ways to interact with your code. Understanding these rules is important for getting good at OOP!
When you start exploring Object-Oriented Programming (OOP), it's important to know about access modifiers. These are special words that control how you can use different parts of your code. The main ones are public, private, and protected. Let’s break them down.
Car
. If it has a public method like startEngine()
, you can call this method from other classes without any problems.public class Car {
public void startEngine() {
System.out.println("Engine started!");
}
}
Car
class has a private property called engineStatus
, you won’t be able to access engineStatus
from any other class. This helps keep data safe.public class Car {
private String engineStatus;
private void checkEngine() {
// Only accessible within Car
}
}
Car
named ElectricCar
, it can use the protected parts of Car
.public class Car {
protected String fuelType;
}
public class ElectricCar extends Car {
public void displayFuelType() {
System.out.println("Fuel Type: " + fuelType);
}
}
Using these keywords wisely helps you decide how much of your class can be used by others. This protects your data and helps create clear ways to interact with your code. Understanding these rules is important for getting good at OOP!