Tutorials

Java OOP Tutorial

All Tutorials Learning Tools Login

Java OOP Tutorial · Chapter 3 of 10

Classes and Objects

Create a class and use it from Main.

Define fields and methods inside a class, then create objects with new.

In CoderKiosk, Main.java stays in the editor and Student.java is loaded as an extra file.

Object creation Try it Yourself »
public class Main {
    public static void main(String[] args) {
        Student student = new Student("Juan Dela Cruz", "BSCS");
        student.introduce();
    }
}
Student.java
public class Student {
    private String name;
    private String course;

    public Student(String name, String course) {
        this.name = name;
        this.course = course;
    }

    public String getName() {
        return name;
    }

    public String getCourse() {
        return course;
    }

    public void introduce() {
        System.out.println("Hello, I am " + name + " from " + course + ".");
    }

    public void displayProfile() {
        System.out.println("Name: " + name);
        System.out.println("Course: " + course);
    }
}

Classroom Tips

  • Public class names must match file names.
  • Run after Try it Yourself so Student.java is included.