DEV Community

nadirbasalamah
nadirbasalamah

Posted on

Java Tutorial - 7 Class and Object

Introduction

The Object Oriented Programming (OOP) is a programming paradigm that based on a real life entities and it's behaviors. The entities can be real entities such as car, student or the abstract entities such as course that taken in a college or university.

Object Oriented Programming's implementaion can be done by using class that represents the real life entity that includes the entity's characteristic defined as a field and the entity's behavior defined as a method or a function in a class.

Create a Class and Object

Class represents as a blueprint of an object. This is the basic syntax to create a class in Java.

modifier class class_name {
    // define some fields..
    // define some methods..
}
Enter fullscreen mode Exit fullscreen mode

In this example, the class called Student is created.

// create a class called Student
public class Student {
    String name;
    String course;

    // create a method
    public void learn() {
        System.out.println("Student name: " + name);
        System.out.println("Learning " + course);
    }
}

Enter fullscreen mode Exit fullscreen mode

The best practice is create a class in a separate file.

Based on the code above, the class called Student is created with the fields called name and course. The behavior is represented as a method called learn() that can be accessed if the object from Student class is created.

The naming convention of a class in Java is using first uppercase, (e.g. Student, ElectricCar)

In this code, the object from Student class is created.

public class MyApp {
    public static void main(String[] args) {
        // instantiate an object from student class
        Student student = new Student();

        // assign a value into the fields
        student.name = "Joe";
        student.course = "Algorithm and Data Structures";

        // call the method
        student.learn();
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Student name: Joe
Learning Algorithm and Data Structures

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the object is created using new keyword followed with the default constructor without the parameter. the constructor (Student()) is used to create an object from a certain class, in this case a Student class. Then, the learn() method can be called from the student object.

Constructor

Constructor is a special function that used to create an object from a class. In the previous code, the default constructor is used. To define a custom constructor, use this basic syntax.

public ClassName(params) {
    // assign the class fields from params
}
Enter fullscreen mode Exit fullscreen mode

In this example, the constructor inside the Student class is created.

// create a class called Student
public class Student {
    String name;
    String course;

    // create a constructor
    public Student(String name, String course) {
        this.name = name;
        this.course = course;
    }

    // create a method
    public void learn() {
        System.out.println("Student name: " + name);
        System.out.println("Learning " + course);
    }
}

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the this keyword is refer to the it's own class. For example, the this.name refers to the name field that defined in a Student class.

If the constructor is defined in a class, the default constructor isn't available. To make sure the default constructor is available, add a default constructor inside class.

// create a class called Student
public class Student {
    String name;
    String course;

    // create a constructor
    public Student(String name, String course) {
        this.name = name;
        this.course = course;
    }

    // create a default constructor
    public Student() {
    }

    // create a method
    public void learn() {
        System.out.println("Student name: " + name);
        System.out.println("Learning " + course);
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the object from Student class is created using custom constructor.

public class MyApp {
    public static void main(String[] args) {
        // instantiate an object with custom constructor
        Student student = new Student("Joe","Algorithm and Data Structures");

        // call the method
        student.learn();
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Student name: Joe
Learning Algorithm and Data Structures

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the name and course fields is assigned using constructor that already defined inside Student class.

Encapsulation

Encapsulation is a mechanism to protect a field's value from direct access. Encapsulation is useful to avoid inconsistency in a field's value. Basically, the private modifier is added to implement encapsulation in a field inside class.

// create a class called Student
public class Student {
    // implement encapsulation in fields
    private String name;
    private String course;

    // create a constructor
    public Student(String name, String course) {
        this.name = name;
        this.course = course;
    }

    // create a default constructor
    public Student() {
    }

    // create a method
    public void learn() {
        System.out.println("Learning " + course);
    }
}

Enter fullscreen mode Exit fullscreen mode

To change or get the value from a fields inside class, use the setter to change the field's value and getter to retrieve the field's value.

// create a class called Student
public class Student {
    // implement encapsulation in fields
    private String name;
    private String course;

    // create a constructor
    public Student(String name, String course) {
        this.name = name;
        this.course = course;
    }

    // create a default constructor
    public Student() {
    }

    // create a method
    public void learn() {
        System.out.println("Learning " + course);
    }

    // using getter
    public String getName() {
        return name;
    }

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

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }
}

Enter fullscreen mode Exit fullscreen mode

This is the code example after the encapsulation mechanism is added in a Student class.

public class MyApp {
    public static void main(String[] args) {
        // instantiate an object with custom constructor
        Student student = new Student("Joe","Algorithm and Data Structures");

        // change the student's name
        student.setName("John");

        // get the student's name and course
        System.out.println("Student's name: " + student.getName());
        System.out.println("Student's course: " + student.getCourse());

        // call the method
        student.learn();
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Student's name: John
Student's course: Algorithm and Data Structures
Learning Algorithm and Data Structures

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the setName() is used to change the name's value. The getter methods including getName() and getCourse() is used to get the value from name and course fields. The learn() method is also available if the object from Student class is created.

Additional keyword and toString() method

The instanceof keyword can be used to check the class type from the created object. In this example, the object called student is checked to make sure that the student is created or instantiated from Student class.

public class MyApp {
    public static void main(String[] args) {
        // instantiate an object from Student class
        Student student = new Student("John","Operating System");

        // check if the student object is instantiated from Student class
        if (student instanceof Student) {
            // print out the class name
            System.out.println(student.getClass().getName());
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

com.nadirbasalamah.Student

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the student object is checked using instanceof keyword. If it's true, the class name from student object is printed out.

The toString() method can be implemented inside defined class. This method is basically converts the created object to object's information in String type. This method is useful to view the field's value from created object and for debugging purpose.

This is the example of using toString() method in Student class.

// create a class called Student
public class Student {
    private String name;
    private String course;

    // create a constructor
    public Student(String name, String course) {
        this.name = name;
        this.course = course;
    }

    // create a default constructor
    public Student() {
    }


    public void learn() {
        System.out.println("Learning " + course);
    }

    public String getName() {
        return name;
    }

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

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }

    // using toString() method
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", course='" + course + '\'' +
                '}';
    }
}

Enter fullscreen mode Exit fullscreen mode

The main class.

public class MyApp {
    public static void main(String[] args) {
        // create an object from Student class
        Student student = new Student("Joe","Operating System");
        // print out the object
        System.out.println(student);
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Student{name='Joe', course='Operating System'}

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the object's information from Student is retrieved. Notice that the toString() method is not called directly in main class because the toString() is called automatically if the created object is printed out.

Enum

Enum type is also available in Java, Enum is basically a data type that allows store many constants. Enum is suitable for some use cases that needs predefined constants. This is the basic syntax of creating enum.

modifier enum enum_name {
    CONSTANT_NAME, ...
}
Enter fullscreen mode Exit fullscreen mode

The modifiers that allowed in enum are public and default modifier.

In this example, the enum called Role is created.

public enum Role {
    STUDENT, LECTURER
}
Enter fullscreen mode Exit fullscreen mode

Based on the code above, the Role has many constants including STUDENT and LECTURER.

The naming convention of constant is using uppercase letter only.

To use the value from defined enum, use this syntax.

enum_name.CONSTANT_NAME
Enter fullscreen mode Exit fullscreen mode

This is the example of using Role enum in Student class.

// create a class called Student
public class Student {
    private String name;
    private String course;
    // create field with Role type
    private Role role;

    // create a constructor
    public Student(String name, String course) {
        this.name = name;
        this.course = course;
        // use the value from enum
        this.role = Role.STUDENT;
    }

    // create a default constructor
    public Student() {
    }


    public void learn() {
        System.out.println("Learning " + course);
    }

    public String getName() {
        return name;
    }

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

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }

    public Role getRole() {
        return role;
    }
}

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the role field is assigned inside constructor using value from Role enum with Role.STUDENT syntax.

Sources

  • Learn more about class and object in this page.

  • Learn more about enum in this page.

I hope this article is helpful for learning the Java programming language. If you have any thoughts or comments you can write in the discussion section below.

Top comments (0)