Skip to content

Classes

Büşra Oğuzoğlu edited this page Jul 12, 2022 · 19 revisions

Object-Oriented Programming:

Object-oriented programming (OOP) involves programming using objects.

An object represents an entity in the real world that can be distinctly identified. A student, a desk, a circle, a button, a television or a Netflix account can be viewed as objects and can be represented as objects.

An object has a unique identity, state, and behavior. Using these, we can model the entities in real life.

  • The state of an object is represented by data fields. These are the properties of said object. For example a Student object may have "name", "GPA", "age", "class" as its data fields.
  • The behavior of an object is defined by methods. To invoke a method on an object is to ask the object to perform an action. For example a TV object may have methods like "turnOn", "turnOff", "changeChannel" etc.

Example Class: Student

How do we model a student as an object?

A student class may have the following properties:

  • Name -> String ("Harry")
  • Age -> int (21)
  • Department -> String ("Magical Studies")
  • Class -> int (2)
  • Graduated -> boolean (false)
  • Grades -> int[] ({96, 94, 84, 76})
  • GPA -> double (3.08)

And may have methods like the following:

  • calculateGPA -> do something with grades
  • addGrade -> add a new grade to grades list
  • changeClass -> change their class, if it is "4" make graduated status true, etc.

Also, it needs to have a special class method, a constructor, that will create a new student.

The student class will look like this:

// Class name
public class Student {

    // Class data fields, class instance variables
    public String name;
    public int age;
    public String department;
    public int class;
    public boolean graduated;
    public int[] grades;
    public double gpa;

    // constructor: constructor is a special class method
    Student(){
        System.out.println("Creating a new student.");
    }

    // Class method(s)
    public void calculateGPA() { ... }
    public void addGrade(int grade) { ... }
    public void changeClass(int class) { ... }

}

UML Diagrams:

Classes and objects can be modeled using a UML (Unified Modeling Language) diagram. From those diagrams, we can see the properties and methods of an object as well as the relationship between different objects. Simple UML diagrams for classes "Netflix" and "Movie" are given below:

netflixclass movieclass
Clone this wiki locally