Object Orientation in Java [class notes]

Learning Goals

The object oriented aspects of Java includes learning:

  • Classes: how we create them and use them
  • Classes as reference type: (and how they are different than primitive types)
  • Encapsulation and access modifiers (details of classes remain inside of classes)
  • Methods: basic behavior and creation
  • field accessors and mutators: controlling interaction with data

Classes in Java

  • Java is object oriented language
  • Objects encapsulate data, operations and usage semantics
    • Objects allow storage and manipulation details to be hidden
    • Objects separates "what" to be done from "how" its implemented
  • Classes provide a structure for describing and creating objects


  • A class is a template for creating an object
    • Class is declared by the class keyword followed by the class name; the body of class is contained inside {} curly braces e.g. class Flight { //statements go here }
    • Java source file normally has the same name as the class e.g. Flight.java
  • A class is made up of both state and executable code
    • Fields: store object state e.g. int passengers; int seats;
    • Methods: Executable code that manipulates state and performs operations e.g. void add1Passenger { }
    • Constructors: Are special case executable code that runs during object creation to set the initial state e.g. Flight() { }
class Flight {
    int passengers;
    int seats;
    Flight() { 
        seats = 150;
        passengers = 0;
    void add1Passenger() {
        if(Passengers < seats)
            passenger += 1;

Using class

  • To use the class, just declaring a variable by Flight ccuToBlr simply allocates a reference for the actual abject we want to use
  • So we need to create an instance of the class. we use the new keyword to create a class instance (a.k.a the object) e.g. ccuToBlr = new Flight()
    • instantiation allocates the memory described the class
    • it also returns back a reference to the declared variable ccuToBlr (hence ccuToBlr is not the object itself rather it is just a reference to the object memory location)
    • We could do this in a single statement as Flight ccuToBlr = new Flight()
    • Then we could call the add1Passenger method by ccuToBlr.add1Passenger(); to increase the passenger count from 0 to 1

Classes are reference types

consider the code snippet below

Flight flight1 = new Flight();
Flight flight2 = new Flight();

System.out.println(flight2.passengers); //output 1

flight2 = flight1; //the value is not copied only memory reference of flight2 changes
System.out.println(flight2.passengers); //output 0


System.out.println(flight2.passengers); //out put 2

Encapsulation and Access Modifiers

  • Internal representation of the object is generally hidden, this idea is called "encapsulation"
  • Java uses "access modifiers" to achieve encapsulation

Some basic access modifiers:

Modifier Visibility Usable on Class Usable on member
No access Modifier Only within own package (a.k.a. package private) Y Y
Public Everywhere Y Y
Private Only within it's own class N * Y

* As private applies to top-level classes: private is applicable to nested-classes

Applying access modifiers

Consider the previous Flight class and we add some access modifier to it:

public class Flight {
    private int passengers;
    private int seats;
    public Flight() { 
        // seats and passengers can be accessed here as they are in class file
        seats = 150;
        passengers = 0;
    public void add1Passenger() {
        if(Passengers < seats)
            passenger += 1;
    private void handleTooMany() { 
        //can't be accessed outside this class file
        System.out.println("Too many");

Naming classes

  • Class name follow the same rule as variable names
  • class name conventions are similar to variables with some differences
    • Use only letter and numbers
    • first character is always a letter
    • However, they follow a style often referred as "Pascal case":
      • start of each word including the first word is upper case and the rest letters are lower case e.g. class BankAccount () { ... }
    • Use simple descriptive nouns
    • Avoid abbreviations unless it's use is more general than full name


  • Methods are executable code that manipulates state and performs operations on the object
    • Each method has a name
      • Same rules and conventions as variables
      • should be a verb or action statement
    • Methods have return type
      • return-type name
      • Use void when no value returned
    • Method can have parameters (typed parameters)
      • return-type name (typed-parameters-list)
      • can be empty
    • Body is contained in {}
      • Note: {} are always required even if the body has only one statement


public class MyClass {
    public void showSum (float x, float y, int count) {
        float sum = x + y;
        for (int i = 0; i < count; i++)

Exiting from a method

  • A method exits for one of the three reasons:
    • The end of the method is reached
    • A return statement is encountered
    • An error occurs
  • Unless there's an error, control returns to the method caller
  • Method returns a single value (unless it's void) it can be
    • A primitive type
    • A reference to an object
    • A reference to an array
      • Arrays are objects in java

Special references : this and null

  • Java provides special references with predefined meanings
    • this is an implicit reference to the current object
      • useful for reducing ambiguity during name collisions
      • Allows an object to pass itself as an parameter


public class Flight {
    private int passengers;
    private int seats;
    // constructors and other methods here
    public boolean hasRoom(Flight f2) {
        int total = this.passengers + f2.passengers;
        return (total <= seats);
    • null is a literal reference to represent an uncreated object
      • it can be assigned to any reference variable


Flight lax1 = new Flight();
Flight lax2 = new Flight();
// add passengers to both flights

Flight lax3 = null;
    lax3 = lax1.createNewWithBoth(lax2);
if(lax3 != null)
    System.out.println("Flights combined");

Field Encapsulation

  • In most cases, a class' fields should not be directly accessible outside the class.
    • It helps to hide the implementation details
    • but we want to remain access to the class available, so we use methods to control field access (called Accessors and Mutators)

Accessors and Mutators

  • Use the Accessors/Mutators pattern to control field access.
  • Accessors retrieve field values
    • They are also called a 'getter'
    • They are named as getFieldName
  • Mutators modifies the field values
    • They are also called a 'setter'
    • They are named as setFieldName


public class Flight {
    private int passengers;
    private int seats;
    // other members elided for clarity
    public int getSeats() {
        return seats;
    public void setSeats(int seats) {
        this.seats = seats;


  • A class is a template for creating an object
    • Declared with class keyword
    • Class instances (a.k.a objects) allocated with new keyword
  • Classes are reference type
  • Use access modifiers to control encapsulation
  • Methods manipulate state and perform operations
    • Use return keyword to exit and/or return a value
  • Fields store object state
    • Interactions to field normally controlled through accessors(getters) and mutators(setters)
Show Comments