OOP

Students.java
public class Students {
    public String name;
    public String gender;
    private int age;
}

Create a class named Students. When the variable in Students class is public you can use it everywhere. When the variable is private you can not use it outside the Students class.

Main.java
public class Main {
    public static void main(String[] args) {
        Students student = new Students();
        student.name = "Mary";
        student.gender = "female";
        System.out.println(student.name + " is " + student.gender);
    }
}

Create an object of Students class, named student. You can assign value to the public variables.

The snippet result is

Mary is female

You can also solve the problem other way.

Students.java
public class Students {
    private String name;
    private String gender;
    private int age;

    public String getName() {
        return name;
    }

    public String getGender() {
        return gender;
    }

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

    public void setGender(String gender) {
        this.gender = gender;
    }
}

Keep the variables private, and use the encapsulation (getter and setter) to method to assign and get the value.

Main.java
public class Main {
    public static void main(String[] args) {
        Students student = new Students();
        student.setName("Mary");
        student.setGender("female");
        System.out.println(student.getName() + " is " + student.getGender());
    }
}

The snippet result is

Mary is female

Third way to solve the problem.

Students.java
public class Students {
    private String name;
    private String gender;
    private int age;

    public Students() {
        this("Mary", "female", 10);
    }

    public Students(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public String getGender() {
        return gender;
    }

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

    public void setGender(String gender) {
        this.gender = gender;
    }
}

Use contstructor to initialize the object first. or assign values.

Main.java
public class Main {
    public static void main(String[] args) {
        Students student = new Students();
        System.out.println(student.getName() + " is " + student.getGender());
    }
}

Create an object of Students class, named student. You can assign value to the public variables.

The snippet result is

Mary is female

Last updated