Today you will learn:
this keywordBy the end, you will understand how to design clean and structured Java classes.
A class is a blueprint for creating objects.
An object is an instance of a class.
class Person {
String name;
int age;
}
A constructor is used to initialize objects.
public Person(String name, int age) {
this.name = name;
this.age = age;
}
Explanation:
this refers to the current object.
It is used to distinguish between class variables and parameters.
this.name = name;
Encapsulation means hiding data and controlling access.
private for fields
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println(name + " is " + age + " years old.");
}
}
Create a class Car with attributes and methods.
Steps:
brand and speedaccelerate and brakeExample:
public class Car {
private String brand;
private int speed;
public Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
public void accelerate() {
speed += 10;
System.out.println("Speed increased to " + speed);
}
public void brake() {
speed -= 10;
System.out.println("Speed decreased to " + speed);
}
public static void main(String[] args) {
Car myCar = new Car("BMW", 50);
myCar.accelerate();
myCar.brake();
}
}