Java OOP
Java Classes
A class is a blueprint or template for creating objects. It defines the structure (attributes) and behavior (methods) that an object will have.
public class Car {
// Fields (attributes or properties)
String color;
int speed;
// Methods (behavior)
void drive() {
System.out.println("The car is driving.");
}
}
In the above example:
Objects and Object Creation
An object is an instance of a class. When you create an object, you are essentially creating a variable of a particular class type that holds data and can perform actions defined within that class.
Car myCar = new Car();
Here:
myCaris an object of the classCar.- The
newkeyword is used to allocate memory for the object and invoke its constructor.
Constructors
A constructor is a special method that initializes a new object. Constructors have the same name as the class and no return type. They are called automatically when an object is created. If you don’t define a constructor, Java provides a default constructor with no parameters.
public class Car {
String color;
int speed;
// Constructor
public Car(String color, int speed) {
this.color = color;
this.speed = speed;
}
}
Usage:
Car myCar = new Car("Red", 150);
In this example:
- The constructor sets initial values for
colorandspeedwhen aCarobject is created.
Access Modifiers: Public and Private
Access modifiers control the visibility of classes, methods, and variables. Java provides several modifiers, but the two most commonly used are public and private.
public class Car {
private String color; // Accessible only within the Car class
public int speed; // Accessible from any class
public String getColor() {
return color; // Accessed through a public method
}
public void setColor(String color) {
this.color = color;
}
}
In the example:
- The
colorfield is private, so it cannot be accessed directly from outsideCar. - Instead, it can be accessed or modified using getters and setters.
Getters and Setters
Getters and setters are methods that provide controlled access to private fields. This is essential for encapsulation, allowing you to protect and control changes to data.
public class Car {
private String color;
private int speed;
// Getter for color
public String getColor() {
return color;
}
// Setter for color
public void setColor(String color) {
this.color = color;
}
}
Usage:
Car myCar = new Car();
myCar.setColor("Blue");
System.out.println(myCar.getColor()); // Outputs: Blue
In this example:
setColorsets the color ofmyCar.getColorretrieves the color ofmyCar.
The Static Keyword
The static keyword makes a field, method, or class variable belong to the class itself, rather than to instances of the class. Static members are shared across all instances of the class, allowing for values or functions common to every object.
public class Car {
private static int carCount = 0;
public Car() {
carCount++; // Increment the static car count for every new Car created
}
// Static method
public static int getCarCount() {
return carCount;
}
}
Usage:
Car car1 = new Car();
Car car2 = new Car();
System.out.println(Car.getCarCount()); // Outputs: 2
In this example:
carCountis a static field, meaning it is shared by all instances.getCarCount()is a static method that retrieves the sharedcarCountacross all instances.
OOP
Object-Oriented Programming (OOP) in Java is a programming paradigm where everything is modeled as objects. The four key principles of OOP are:
Encapsulation
Encapsulation is the concept of bundling data and methods together and restricting access to certain parts of an object.
class Car {
private String model;
private int year;
// Getter and Setter methods
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
Inheritance
Inheritance allows a class to acquire properties and methods from another class.
class Vehicle {
protected String brand = "Toyota";
public void honk() {
System.out.println("Beep beep!");
}
}
class Car extends Vehicle {
private String model;
public Car(String model) {
this.model = model;
}
public void displayInfo() {
System.out.println(brand + " " + model);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Corolla");
myCar.honk(); // Output: Beep beep!
myCar.displayInfo(); // Output: Toyota Corolla
}
}
Polymorphism
Polymorphism allows one method to have different implementations based on the object that calls it. It can happen at compile-time or runtime.
Method Overloading (Compile-time Polymorphism)
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(10, 20)); // Output: 30
System.out.println(calc.add(10, 20, 30)); // Output: 60
}
}
Method Overriding (Runtime Polymorphism)
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks
}
}
Abstraction
Abstraction hides complex implementation details and shows only the necessary functionalities to the user.
abstract class Animal {
public abstract void sound(); // Abstract method
public void sleep() {
System.out.println("Sleeping...");
}
}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.sound(); // Output: Cat meows
myCat.sleep(); // Output: Sleeping...
}
}
Semantic portal