MyMisPal
← Java lessons
Lesson 7 of 9

Classes and objects

JAVA
class Employee {
    private String name;
    private double salary;

    Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    void giveRaise(double percent) {
        salary += salary * percent / 100;
    }

    double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return name + ": " + salary;
    }
}

public class Main {
    public static void main(String[] args) {
        Employee lina = new Employee("Lina", 13500);
        lina.giveRaise(10);
        System.out.println(lina);
        System.out.println(lina.getSalary() > 14000);
    }
}
Output
Lina: 14850.0
true

A constructor has the class's name and runs when you create an object with new. Encapsulation means keeping data private and exposing it through methods like getSalary(), so nothing outside the class can set an invalid salary.

Same idea in both languages
Python
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
Java
class Employee {
    private String name;
    private double salary;

    Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }
}
Spotted a mistake on this page, or have an idea to improve the site?