Skip to main content

Command Palette

Search for a command to run...

3) Classes and Methods in Java

Introduction to the basics of classes and methods in Java

Updated
•3 min read•View as Markdown
3) Classes and Methods in Java
A

Product-oriented Software Engineer with a solid understanding of web programming fundamentals and software development methodologies such as agile and scrum.

What is a Class in Java?

A class in Java is a blueprint for creating objects. It defines the properties (fields/attributes) and behaviors (methods) that the objects created from the class can have.

The components of a class are:

  • Fields: Variables that store the state or attributes of an object.

  • Methods: Functions inside a class that define its behavior.

  • Constructor: A special method used to initialize objects.

Defining a Class

public class Car {
    // Fields (attributes)
    String brand;
    String color;
    int year;

    // Constructor is the method that runs when the class is instantiated
    public Car(String brand, String color, int year) {
        this.brand = brand;
        this.color = color;
        this.year = year;
    }

    // Method (behavior)
    public void displayDetails() {
        System.out.println("Brand: " + brand + ", Color: " + color + ", Year: " + year);
    }

}

Creating an Object

To use a class, create an instance (object) of it.

public class Main {
    public static void main(String[] args) {
        // Create an object of the Car class
        Car myCar = new Car("Tesla", "Red", 2023);

        // Access the object's methods
        myCar.displayDetails();  // Output: Brand: Tesla, Color: Red, Year: 2023
    }
}

Access Modifiers

Access modifiers control the visibility of fields and methods:

• public – Accessible from anywhere.

• private – Accessible only within the class.

• protected – Accessible within the package and by subclasses.

• (default) – Accessible within the package.

public class Person {
    private String name;  // Private field

    public String getName() {
        return name;  // Public method to access private field
    }

    public void setName(String name) {
        this.name = name;
    }
}

Static Fields and Methods

Static members belong to the class rather than any specific object.

public class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }
}

Usage:

int sum = MathUtils.add(5, 10);  // No need to create an object
System.out.println(sum);  // Output: 15

Inheritance

Java allows one class to inherit from another.

class Vehicle {
    public void start() {
        System.out.println("Vehicle is starting");
    }
}

class Car extends Vehicle {
    public void honk() {
        System.out.println("Car is honking");
    }
}

Usage:

Car myCar = new Car();

myCar.start();  // Inherited from Vehicle
myCar.honk();   // Defined in Car

Encapsulation

Encapsulation restricts direct access to fields by using getters and setters.

public class BankAccount {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
}

Polymorphism

Polymorphism allows methods to behave differently based on the object calling them.

class Animal {
    public void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Dog();
        myAnimal.makeSound();  // Output: Dog barks
    }
}

Abstract Classes and Interfaces

Abstract Class

abstract class Shape {
    abstract void draw();
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing a circle");
    }
}

Interface

interface Animal {
    void makeSound();
}

class Cat implements Animal {
    public void makeSound() {
        System.out.println("Cat meows");
    }
}

This covers the fundamentals of Java classes. Try these examples and explore more concepts like this keyword, method overloading, and more advanced topics as you gain experience!

Learning Java

Part 4 of 26

In this series, I will break down the task of learning java into smaller actionable steps and work on them topic by topic while trying to provide observability into my learning process.

Up next

4) Conditional Statements in Java

Ways to control the flow of a Java program