timerring

07 Classes and Interfaces

January 9, 2024 · 3 min read
Tutorial
Java
If you have any questions, feel free to comment below. Click the block can copy the code.
And if you think it's helpful to you, just click on the ads which can support this site. Thanks!

7.1 Classes and Objects #

A class defines an entirely new data type containing a group of variables and functions; an object is an instance of that class.

Defining Student as a class represents the abstract concept of a “student.” Each student is then an object (instance) of the Student class.

7.1.1 Source File Declaration Rules #

  • A source file can have only one public class.
  • A source file can have multiple non-public classes.
  • The source file’s name should match the name of its public class.
  • In each source file, write the package statement first (similar to a file path), then the import statements, and finally define the classes.

7.1.2 Defining Classes #

  • public: accessible to all objects
  • private: accessible only within the class itself
  • protected: accessible within the same package or from subclasses
  • No modifier: accessible within the same package
  • The differences between static (marked static) member variables/functions and ordinary member variables/functions:
    • There is only one copy of each static member variable/function in the class, shared by all objects of the class. (It is best to access static variables using the class name, as in Student.x.)
    • Each object of the class has its own copy of ordinary member variables/functions.
    • Static functions can call only static functions/variables; ordinary functions can call both ordinary and static functions/variables.
class Point {
		// Member variables
    private int x;
    private int y;
		// Constructor
    public Point(int x, int y) {
		    // this.x refers to the member variable
		    // x is a parameter (local variable)
        this.x = x;
        this.y = y;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public String toString() {
        return String.format("(%d, %d)", x, y);
    }
}
7.1.3 Class Inheritance #

Each class can inherit from only one class.

class ColorPoint extends Point {
    private String color;

    public ColorPoint(int x, int y, String color) {
        super(x, y);
        this.color = color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String toString() {
        return String.format("(%d, %d, %s)", super.getX(), super.getY(), this.color);
    }
}
7.1.4 Polymorphism in Classes #

For example, in LoL, every hero greets at the start of a game. Checking each hero with if-else statements would be cumbersome, so it is better to use Hero as the base class for each type of hero and call the base class’s greet method. Because the subclass’s greet function takes precedence, each hero produces a different result.

public class Main {
    public static void main(String[] args) {
        Point point = new Point(3, 4);
        Point colorPoint = new ColorPoint(1, 2, "red");

        // Polymorphism: instances of the same class call the same function but produce different results
        System.out.println(point.toString());
        System.out.println(colorPoint.toString());
    }
}

7.2 Interfaces #

An interface is similar to a class. It is mainly used to define the functions a class must contain.

An interface can inherit other interfaces, and a class can implement multiple interfaces.

7.2.1 Defining Interfaces #

Without an explicit modifier in an interface, the default is public.

interface Role {
    public void greet(); // Omitting public still makes it public by default
    public void move();
    public int getSpeed();
}
7.2.2 Interface Inheritance #

Each interface can inherit multiple interfaces.

interface Hero extends Role {
    public void attack();
}
7.2.3 Implementing Interfaces #

Each class can implement multiple interfaces.

class Zeus implements Hero {
    private final String name = "Zeus";
    public void attack() {
        System.out.println(name + ": Attack!");
    }

    public void greet() {
        System.out.println(name + ": Hi!");
    }

    public void move() {
        System.out.println(name + ": Move!");
    }

    public int getSpeed() {
        return 10;
    }
}
7.2.4 Polymorphism in Interfaces #

class Athena implements Hero {
    private final String name = "Athena";
    public void attack() {
        System.out.println(name + ": Attack!!!");
    }

    public void greet() {
        System.out.println(name + ": Hi!!!");
    }

    public void move() {
        System.out.println(name + ": Move!!!");
    }

    public int getSpeed() {
        return 10;
    }
}

public class Main {
    public static void main(String[] args) {
        Hero[] heros = {new Zeus(), new Athena()};
        for (Hero hero: heros) {
            hero.greet();
        }
    }
}

Related readings


<< prev | 06 Functions Continue strolling 08 Common... | next >>

If you want to follow my updates, or have a coffee chat with me, feel free to connect with me: