Chapter[6]: Understanding Java Classes and Keywords with Simple Car Examples
Learning Java is like learning to build a model of real-life objects, using code to create a blueprint for things like cars, and Hotels. In Java, classes are like blueprints that describe an object’s characteristics and actions, while keywords like public
, private
, and static
help organize and secure how this blueprint is used. Let’s walk through the basics of creating a Car
class, with some easy code snippets to help you understand each concept.
+-------------+
| Car |(A Blueprint of a car)
+-------------+
| Attributes: |
| - type |
| - color |
| - brand |
| - year |
+-------------+
|
--------------------------------------------
| | |
+-------------+ +-------------+ +-------------+
| Car1 | | Car2 | | Car3 |
+-------------+ +-------------+ +-------------+
| Attributes: | | Attributes: | | Attributes: |
| - type: | | - type: | | - type: |
| Sedan | | Hatchback | | SUV |
| - color: | | - color: | | - color: |
| Red | | Blue | | Black |
| - brand: | | - brand: | | - brand: |
| Toyota | | Ford | | BMW |
| - year: | | - year: | | - year: |
| 2020 | | 2018 | | 2022 |
+-------------+ +-------------+ +------------
What is a Class in Java?
A class in Java is the foundation for creating objects. Imagine you’re designing a Car
class. It’s a template for creating individual car objects, each with its unique details and actions.
// This creates a basic blueprint called Car
public class Car {
// Attributes and methods will go here
}
Defining Car Attributes with public
and private
In our Car
class, we’ll add attributes to define a car’s properties and methods to describe what it can do.
Example: Public Methods
These are the functionalities anyone can use or interact with:
1: Start Engine: Anyone with the key can start the car, so this method should be public.
public void startEngine() { ... }
2: Turn on Headlights: A basic functionality accessible to anyone in the car.
public void turnOnHeadlights() { ... }
3: Open Door: With the right key or mechanism, anyone can open the door.
public void openDoor() { ... }
4: Honk Horn: Anyone inside can honk, so it should be public.
public void honkHorn() { ... }
Private Methods
These involve internal operations or data that only the car (or its owner) should handle:
1: Check Fuel Level: Only the car’s system or owner needs to know how much fuel is left; no one outside should access this directly.
private void checkFuelLevel() { ... }
2: Adjust Internal Electronics: Settings like calibrating sensors or internal diagnostics shouldn’t be publicly accessible.
private void calibrateSensors() { ... }
3: Engine Control: Internal operations like controlling fuel injection or ignition systems should remain private.
private void controlEngine() { ... }
4: Lock Control System: The logic for locking or unlocking the car should stay private; only accessible through public methods like lockCar()
or unlockCar()
.
private void lockControlSystem() { ... }
public
: Allows everyone (outside the class) to see or modify the attribute. Here,color
is public because anyone can see a car's color.private
: Restricts access so that only theCar
class itself can interact with this attribute. Here, Chassis Number is private because it’s information only the owner should know.
Adding Actions with Methods
Methods define actions the car can take, like starting the engine or driving. Here’s how public
and private
come into play:
- Example: Since anyone with the key can start the engine, the
startEngine
method can bepublic
. But if the car needs to check internal components (like a fuel level), that could be a private method since it’s only relevant to the car itself.
public void startEngine() { System.out.println("Engine started."); }
private void checkFuel() { System.out.println("Fuel level is sufficient."); }
public void startEngine()
: This method ispublic
because we want it accessible to anyone trying to start the car.private void checkFuel()
: This isprivate
because it’s an internal check the car does for itself.
Using static
for Shared Attributes
Sometimes, we want certain data to belong to the class as a whole, not to individual objects. For example, we might want to keep track of how many Car
Objects (called instances at runtime) are created using the Car class as the blueprint.
- Example: The
carCount
attribute could bestatic
because it should apply to all cars, not just one specific car.
public static int carCount = 0; // shared by all cars
public Car() { carCount++; // Increment the car count each time a new car is created
}
public static int carCount
: This variable is shared across all instances ofCar
. Every time we create a newCar
object,carCount
will increment by 1.carCount++
in the constructor: By placingcarCount++
inside the constructor, it increments each time a new car is created, giving us a total count of all cars.
The public static void main(String[] args)
Method: Starting the Program
The public
in public static void main
means that the main method is open for the JVM (the program that runs your Java code) to see and use it. This is important because the JVM needs to access this method to start your program.
In Java, every application starts with a main
method. Each part of public static void main(String[] args)
has a purpose:
public static void main(String[] args) {
Car myCar = new Car(); // Create a new Car object
myCar.startEngine(); // Start the car's engine
}
public
: Themain
method needs to be public so the Java runtime can access it to start the program.static
: We usestatic
becausemain
belongs to the class itself, and we don’t need an object to run it.void
: This method doesn’t return any value, so it’svoid
.main
: This specific method name tells Java where the program starts.String[] args
: Allows input from the command line, as discussed.
Putting it All Together: Simple Car Class Example
Here’s how our Car
class might look with all these concepts combined:
public class Car { //A Car class is created like this
public String color; // anyone can see the car's color
private int mileage; // only the car knows its mileage
public static int carCount = 0; // shared by all cars
public Car(String color, int mileage) { // A Cunstructor
this.color = color; //public in nature
this.mileage = mileage; //private in nature
carCount++; // count each new car(static in nature)
}
// Public method to start the engine
public void startEngine() {
System.out.println("Engine started.");
}
// Private method for an internal fuel check
private void checkFuel() {
System.out.println("Fuel level is sufficient.");
}
// Public method to get the mileage
public int getMileage() {
return mileage; // allows limited access to private mileage
}
public static void main(String[] args) {
Car myCar = new Car("Red", 15000); // create a new car
myCar.startEngine(); // start the engine
System.out.println("Car color: " + myCar.color); // access public attribute
System.out.println("Car mileage: " + myCar.getMileage()); // get mileage through a public method
System.out.println("Total cars: " + Car.carCount); // access static variable
}
}
Summary
public
: Accessible to anyone, likecolor
andstartEngine
. Think of it like a car’s exterior—visible to anyone.private
: Only accessible inside the class, likemileage
andcheckFuel
. This is like internal parts of a car that only a mechanic (or the car itself) needs to access.static
: Shared across all instances, likecarCount
, which keeps a record of all cars.main
method: The starting point for any Java program.
With these basics, you’re set to start building your own classes in Java!
Happy Coding!