Mark Danishevsky

Tutorials: Object Oriented Programming

Back to tutorials home

OOP Navigation

What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that organizes code using objects—real-world representations of things. It helps developers structure programs in a more modular, understandable, and reusable way.

Introduction of Object Oriented Programming | GeeksforGeeks

Definitions of OOP concepts:

UML Representation

Classes are commonly represented using Unified Modeling Language (UML) structure. A simple example of UML is below:

First we see that a class has three sections:

  1. The name of the class, in our case ClassName (make sure it follows the naming conventions for classes - it must begin with a capital letter)
  2. The attributes of the class, their respective data type and their access symbol
    • Done in the format: [access symbol] [variable name]: [variable type]
  3. The methods of the class, their parameters (if applicable) and their return types.
    • Done in the format: [access symbol] [method name]([parameters and respective types]): [output type (or void if none)]
    • Constructor format: [access symbol] [class Name]([parameters and respective types])

Next we see that an instance of a class has 2 sections:

  1. The name of the instance, following all naming conventions
  2. The attributes of the method
    • [variable name] = [value of variable]

Note: one class can have multiple instances.

The symbols before a method or attribute in a class are bellow ([UMLDiagrams.org] Visibility in UML):

Symbol Meaning Access Level Example
+ Public Accessible from anywhere + drive(): void
- Private Accessible only inside the class - mileage : int
# Protected Accessible inside the class and its subclasses # model : String
~ Package (default) Accessible within the same package ~ speed : int

Note that I will only be using '+' and '-' (public and private) in my diagrams. It is good practice to have all attributes set to private, and have other classes access the values of these attributes using a getter method and set the values of these attributes using a setter method.

Here is a UML example of creating three instances of a class Car.

The equivalent of the UML above but in code would be:

In another class we would have:

Inheritance Introduction

Inheritance is a key concept in Object-Oriented Programming (OOP) that allows a class to inherit properties and methods from another class.

Bellow are some definitions of common inheritance terminologies:

Superclass: A superclass is a general class (like Animal) that contains common attributes and methods. It is the class being inherited from (the parent or base class).

Subclass: A subclass is a more specific class (like Dog) that inherits the properties of the superclass using the extends keyword. It is the class that inherits from the superclass, so it is the child.

Extends: The Java keyword used to declare that one class inherits from another.

Diagram of if-else if-else structure

Here, the class ExampleSubClass is a superclass of SuperClass.

[W3 Schools] Java Inheritance (Subclass and Superclass)
Oracle Java Tutorials - Inheritance

Inheritance Example

In this example, if we created an instance of Animal, we could run only the method makeSound. However, if we created an instance of Dog, we could run both makeSound and fetch because the Dog inherits the methods of Animal.

Is-a and Has-a relationship

What is the difference between "IS -A" relationship and "HAS-A" relationship in Java? - Stack Overflow

Visual Example

In the scheme below, I create classes to categorize vertebrates:


super() keyword

The super keyword is used in a subclass to refer to its immediate superclass.

It's commonly used for calling the superclass constructor:

It can also be used to access a superclass method or field:

Constructors

In Java, constructors are not inherited, but when a subclass is created, it must call a constructor of its superclass, either automatically or using super().

Inheritance Code Example

I will now create a very similar scenario to the one above (Vertebrates, Warm Blooded, Cold Blooded, …) with the removal of Fish and Amphibian, for the sake of simplicity. We will first model the program in Java:

Now I will run in a separate class Main several commands, explain what they will output and why.

Code (in Main.java) Output Explanation
Vertebrate v = new Vertebrate();
v.move();
The vertebrate moves. Calls the base class method directly.
WarmBlooded w = new WarmBlooded();
w.move();
The warm-blooded animal walks or flies. Uses overridden method in WarmBlooded.
Bird b = new Bird();
b.move();
The warm-blooded animal walks or flies. The bird flies. Bird overrides move() and calls super.move() to include WarmBlooded’s version.
Vertebrate v2 = new Bird();
v2.move();
The warm-blooded animal walks or flies. The bird flies. Polymorphism: although the reference type is Vertebrate, the actual object’s method in Bird is called.
ColdBlooded c = new ColdBlooded();
c.move();
The cold-blooded animal crawls. Uses overridden method in ColdBlooded.
Reptile r = new Reptile();
r.move();
The cold-blooded animal crawls. The reptile slithers. Reptile calls super.move() to include the ColdBlooded behavior.
Vertebrate v3 = new Mammal();
v3.move();
The warm-blooded animal walks or flies. The mammal walks. Shows polymorphism + inheritance through super.
Bird b2 = (Bird) new Vertebrate();
b2.move();
Runtime Error: ClassCastException Cannot cast a base class object to a derived type. Java throws an error during execution.
((WarmBlooded) new Mammal()).move(); The warm-blooded animal walks or flies. The mammal walks. Valid cast up the hierarchy. move() from Mammal is still called because the actual object is Mammal.
Mammal m = (Mammal) new WarmBlooded();
m.move();
Runtime Error: ClassCastException Trying to downcast to Mammal, but object is actually only a WarmBlooded. This is not allowed unless it was originally a Mammal.

Abstract Classes

An abstract class provides a partial implementation for its subclasses and cannot be instantiated on its own. Below is a Java example:

In this example, Dog inherits from Animal and must implement makeSound(). The method eat() is inherited as-is.

Interfaces

An interface defines a contract that a class agrees to follow. Here's an example in Java:

Here, Bird implements Flyable and provides an implementation of the fly() method.

Oracle Java Tutorials - Interfaces

When to Use What?

Feature Abstract Class Interface
Can contain method implementations? Yes Only with default or static (Java 8+)
Can have constructors? Yes No
Can extend multiple? No (single inheritance only) Yes (a class can implement multiple interfaces)
Can contain variables? Yes (instance variables) Yes (constants only)

Mistakes to Avoid

Forgetting you can only call methods found or inherited by the reference type
If you have a variable of type SuperClass (let's say Vertebrate) but is instantiated using the constructor of SubClass (let's say Bird), you can't simply run a method found only in the superclass. To do this you would need to cast the variable to the type SubClass (Bird), and then run the method. You can only call methods declared in the reference type (Vertebrate), even if the object is a Bird. You'd need to cast:

Incorrect Casting Leading to ClassCastException
You cannot cast a superclass to a subclass. This code would compile, but it would crash at runtime.

Forgetting a private method cannot be inherited
A subclass will not inherit a private method from a superclass. If you attempt to call the method from the subclass, you will get a compile error.