Loading W Code...
Master Object-Oriented Programming with Java - the most popular enterprise language.
Learn how to define classes and create objects in Java
A class is a blueprint or template for creating objects. It defines properties (fields) and behaviors (methods).
An object is an instance of a class - a concrete entity created from the class blueprint.
// Defining a class
public class Car {
// Fields (properties)
String brand;
String color;
int speed;
// Constructor
public Car(String brand, String color) {
this.brand = brand;
this.color = color;
this.speed = 0;
}
// Methods (behaviors)
public void accelerate() {
speed += 10;
System.out.println(brand + " is now going " + speed + " km/h");
}
public void brake() {
speed = Math.max(0, speed - 10);
System.out.println(brand + " slowed down to " + speed + " km/h");
}
}
// Creating objects
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Red");
Car yourCar = new Car("Honda", "Blue");
myCar.accelerate(); // Toyota is now going 10 km/h
yourCar.accelerate(); // Honda is now going 10 km/h
}
}
class keyword to define a classnew keyword to create objectsthis refers to the current objectHide internal data and provide controlled access through getters/setters
Encapsulation is bundling data (fields) and methods that operate on that data within a class, and restricting direct access to some components.
private: Only accessible within the classprotected: Accessible within package and subclassespublic: Accessible from anywheredefault: Accessible within the same packagepublic class BankAccount {
// Private fields - hidden from outside
private String accountNumber;
private double balance;
// Constructor
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
// Getter - controlled read access
public double getBalance() {
return balance;
}
// No setter for accountNumber - it's read-only
public String getAccountNumber() {
return accountNumber;
}
// Controlled modification through methods
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
}
}
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
return true;
}
System.out.println("Insufficient funds!");
return false;
}
}
Create new classes that inherit properties and methods from existing classes
Inheritance allows a class (child/subclass) to inherit properties and methods from another class (parent/superclass).
// Parent class (Superclass)
public class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class (Subclass)
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age); // Call parent constructor
this.breed = breed;
}
// New method specific to Dog
public void bark() {
System.out.println(name + " says: Woof! Woof!");
}
// Override parent method
@Override
public void eat() {
System.out.println(name + " the " + breed + " is eating dog food");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy", 3, "Golden Retriever");
myDog.eat(); // Overridden method
myDog.sleep(); // Inherited method
myDog.bark(); // Dog's own method
}
}
extends keyword for inheritancesuper refers to the parent class@Override annotation for method overridingSame method name, different implementations based on context
Polymorphism means "many forms". It allows objects to be treated as instances of their parent class while behaving according to their actual class.
public class Calculator {
// Same method name, different parameters
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
public class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
public double area() {
return 0;
}
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing a rectangle " + width + "x" + height);
}
@Override
public double area() {
return width * height;
}
}
// Usage - Polymorphism in action
public class Main {
public static void main(String[] args) {
Shape[] shapes = {
new Circle(5),
new Rectangle(4, 6),
new Circle(3)
};
for (Shape shape : shapes) {
shape.draw(); // Calls the appropriate method
System.out.println("Area: " + shape.area());
}
}
}
Hide complex implementation details and show only essential features
Abstraction is hiding complex implementation details and showing only the necessary features of an object.
// Abstract class - cannot be instantiated
public abstract class Vehicle {
protected String brand;
public Vehicle(String brand) {
this.brand = brand;
}
// Abstract method - must be implemented by subclasses
public abstract void start();
public abstract void stop();
// Concrete method - can be used as-is
public void displayBrand() {
System.out.println("Brand: " + brand);
}
}
public class Car extends Vehicle {
public Car(String brand) {
super(brand);
}
@Override
public void start() {
System.out.println(brand + " car engine started with key");
}
@Override
public void stop() {
System.out.println(brand + " car engine stopped");
}
}
public class ElectricCar extends Vehicle {
public ElectricCar(String brand) {
super(brand);
}
@Override
public void start() {
System.out.println(brand + " electric car started silently");
}
@Override
public void stop() {
System.out.println(brand + " electric car powered down");
}
}
public interface Flyable {
void fly();
void land();
}
public interface Swimmable {
void swim();
}
// A class can implement multiple interfaces
public class Duck implements Flyable, Swimmable {
@Override
public void fly() {
System.out.println("Duck is flying");
}
@Override
public void land() {
System.out.println("Duck has landed");
}
@Override
public void swim() {
System.out.println("Duck is swimming");
}
}
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Can have both abstract and concrete | All abstract (Java 8+ can have default) |
| Variables | Can have instance variables | Only constants (public static final) |
| Inheritance | Single inheritance | Multiple interfaces |
| Constructor | Can have constructor | Cannot have constructor |