Object Oriented Programming

Conceptual and Principles

Agenda

  1. Understanding Programming Paradigms
  2. Object Oriented Programming: What and Why?
    • Conceptual definitions
    • Comparison against Procedural programming
  3. OOP Design Principles
    • Encapsulation
    • Inheritance
    • Polymorphism
    • Abstraction and Interfaces
  4. Quiz

Demo Environment:

1. Language: ​JAVA

2. OS: Windows 10 64 Bit

3. Editor: Slides.com

Programing Paradigms

  • A style, or 'way' of programming
  • Originates from the word 'Paradigm', which means a way of doing something

  • A way to classify or categorize programming languages, based on their features

Breakdown

  1. Imperative
    • Programmer instructs machine how to change its state. Control flow is explicit.

      1. Procedural (C, C++)

      2. OOP (C++, Java, C#)

  2. Declarative
    • Programmer declares properties of the desired results, but not how to compute it. Control flow is implicit.

      • ​functional (Lisp, ErLang, Haskell)

      • logic (Prolog, Datalog)

      • mathematical (Matlab, R)

Object Oriented Programming

  1. PC hardware assembly
  2. Car assembly
  3. Software stand-point

Conceptual Definitions

Classes

:model of real world object

Objects

:instances of a class

Attributes

:the state or properties of the object

Methods

:the behavior or 'actions' of the object

Cat

Tom

:Grey

: 2 years old

:Hungry

meow()

sleep()

eat()

Creating a Class and an Object

public class Cat {
  String name;
  int age;
  String color;
  String state = "OK";

  void meow(){
    System.out.println("MEOOOOOWWW!");
  }

  void sleep(){
    System.out.println("ZZzzzzzzz...");
  }

  public static void main(String[] args){
    Cat tom = new Cat();

    tom.name = "Tom";
    tom.age = 2;
    tom.color = "Grey";

    System.out.println("The cat's name is " + tom.name);
    System.out.println(tom.name + " is " + tom.age + " years old.");
    System.out.println("Tom is " + tom.color);
    System.out.println("Tom is " + tom.state);

  }
}

attributes

methods

Setting attributes without a constructor

Main method, to unit test a class

Constructors

public class Cat2 { // name of class needs to be same is name of file
  String name;
  int age;
  String color;
  String state = "OK";

  void meow(){
    System.out.println("MEOOOOOWWW!");
  }

  void sleep(){
    System.out.println("ZZzzzzzzz...");
  }

  // name of constructor is same as name of class
  public Cat2(String name, int age, String color, String state){
    System.out.println("A new cat object is created!");
    this.name = name;
    this.age = age;
    this.color = color;
    this.state = state;
  }

  public static void main(String[] args){
    Cat2 tom = new Cat2("Tom", 4, "Black", "Angry");
    // Cat2 tom = new Cat2("Tom", 4, "Black", "Angry", 25); //compilation error
    // Cat2 tom = new Cat2(4, "Tom", "Black", "Angry", 25); //compilation error //order matters

    System.out.println("The cat's name is " + tom.name);
    System.out.println(tom.name + " is " + tom.age + " years old");
    System.out.println("Tom is " + tom.color);
    System.out.println("Tom is " + tom.state);

  }
}

Creating cat object with a constructor

OOP vs Procedural 

Why do we need OOP?

In procedural programming;

  1. Functions are less reusable
  2. No encapsulation - any functions is available to anyone
  3. Codes are not modular - hard to maintain and fix bugs 

In OOP;

  1. All classes are reusable
  2. Encapsulation allows object data protection. Private attributes without setters and getters are completely protected
  3. Codes modular - easier to maintain and fix bugs 

OOP Design Principles

  1. Encapsulation
  2. Abstraction
  3. Inheritance
  4. Polymorphism

Encapsulation

"Information hiding":

Hiding data implementation by restricting access to mutators and accessors

(a.k.a setters and getters).

  • Protect data implementation
  • Provide users only with essential information for (restricted manipulation), without internal details.

  • Laptop user example

  • Get only allowed attributes

  • Validate values before setting them

without encapsulation

public class Cat2 { // name of class needs to be same is name of file
  String name;
  int age;
  String color;
  String state = "OK";

  void meow(){
    System.out.println("MEOOOOOWWW!");
  }

  void sleep(){
    System.out.println("ZZzzzzzzz...");
  }

  // name of constructor is same as name of class
  public Cat2(String name, int age, String color, String state){
    System.out.println("A new cat object is created!");
    this.name = name;
    this.age = age;
    this.color = color;
    this.state = state;
  }

  public static void main(String[] args){
    Cat2 tom = new Cat2("Tom", -4, "Black", "Angry");
   
    System.out.println("The cat's name is " + tom.name);
    System.out.println(tom.name + " is " + tom.age + " years old");
    System.out.println("Tom is " + tom.color);
    System.out.println("Tom is " + tom.state);

  }
}

negative number for age should NOT be allowed

with encapsulation (Cat3.java)

public class Cat3 { 
  private String codeAuthor = "Asyrul Hafetzy";
  private String name;
  private int age;

  void meow(){
    System.out.println("MEOOOOOWWW!");
  }
  void sleep(){
    System.out.println("ZZzzzzzzz...");
  }
  public String getName(){
    return name;
  }
  public int getAge(){
    return age;
  }
  public void setName(String n){
    name = n;
  }
  public void setAge(int a){
    if(a > 0){
      age = a;
    }
    else{
      throw new RuntimeException("Invalid age number!");
    }
  }
  public void printCat(){
    System.out.println("The cat's name is " + name);
    System.out.println(name + " is " + age + " years old");
  }

  // constructor
  public Cat3(String name, int age){
    System.out.println("A new cat object is created!");
    this.name = name;
    this.age = age;
  }
}

Value validation

Set variables to private

Setters and getters

Print Function

Main method (main.java)

public class main{
  public static void main(String[] args){
    Cat3 tom = new Cat3("Tom", 4);
    tom.printCat();

    // tom.name = "Ali";
    // tom.printCat();

    // tom.setName("Ali");
    // tom.printCat();

    tom.setAge(-4);
    tom.printCat();

    // System.out.println(tom.name); //error
    // System.out.println(tom.getName());
    System.out.println(tom.codeAuthor);

  }
}

Inheritance

Allows class to inherit common characteristics or methods from a more general class.

 

IS-A Relationship

  • A Cat IS-An Animal
  • A Car IS-A Vehicle
  • Prevent code repetition/ duplication
  • DRY - Dont Repeat Yourself
  • Allows abstraction to be made possible
  • Defines a common protocol for a set of classes related through inheritance.

Method Overriding

Overriding parent class's methods

Object Structure with Duplicated Codes

Cat

name
age
breed

move()
makeNoise()
sleep()

Dog

name
age
breed

move()
makeNoise()
sleep()

Wolf

name
age
breed

move()
makeNoise()
sleep()

Every class is repeating the same attributes and methods. Not a good design

Ideal Object Structure

Cat

move()
makeNoise()

Animal

name
age
breed

Cow

move()
makeNoise()

move()
makeNoise()

sleep()

Dog

move()
makeNoise()

Superclass

Subclass

  • Subclasses inherit all attributes and methods of parent class
  • Parent's methods can be modified in subclasses by method overriding

Stripe

Color

Creating a Animal Superclass (Animal.java)

public class Animal {
  String name;
  int age;
  String breed;

  public Animal(String name, int age, String breed){
    this.name = name;
    this.age = age;
    this.breed = breed;

    System.out.println("A new animal instance is created!");
  }

  public String move(){
    String a = "Walkinggg....";
    return a;
  }

  public String makeNoise(){
    //empty
    return "";
  }

  public void sleep(){
    System.out.println("ZZzzzzz....");
  }
}

attributes

Constructor

Methods

Creating a Cat Subclass (CatInherited.java)

public class CatInherited extends Animal{
  String stripe;

  public CatInherited(String name, int age, String breed, String stripe){
    super(name, age, breed);
    this.stripe = stripe;

    System.out.println("A new Cat instance is created!");
  }

  public void printCat(){
    System.out.println("The cat's name is " + name);
    System.out.println(name + " is " + age + " years old");
    System.out.println(name + " is a " + breed + " breed");
    System.out.println(name + " has " + stripe + " stripes");
    System.out.println(name + " moves by " + move());
  }
}

Cat has specific property called stripe

Calling Superclass

Constructor

Subclass object automatically inherits parent class's properties

Using 'extends' keyword

Creating a Cow Subclass (CowInheritance.java)

public class CowInheritance extends Animal {

    public CowInheritance(String name, int age, String breed){
      super(name, age, breed);

      System.out.println("A new Cow instance is created!");
    }

    //method overriding
    public String makeNoise(){
      return "MooooOOOOooo!!!";
    }

    public String move(){
      return "Walking verrryyyy slowwwlyyyy";
    }

    public void printCow(){
      System.out.println("The cow's name is " + name);
      System.out.println(name + " is " + age + " years old");
      System.out.println(name + " is a " + breed + " breed");
      System.out.println(name + " moves by " + move());
      //explicitly invoking super's method
      System.out.println(name + " moves by " + super.move());
    }
}

Modification to parents class's methods; Method Overriding

use 'super' keyword to explicitly invoke superclass method

Main class (mainInheritance.java)

public class mainInheritance{
  public static void main(String[] args){
    CatInherited tom = new CatInherited("Tom", 3, "Russian Blue", "Black and white");
    tom.printCat();

    System.out.println(" ************************* ");

    CowInheritance billy = new CowInheritance("Billy", 3, "Angus Cattle");
    billy.printCow();

  }
}

BOTH superclass and subclass constructors are invoked

Method overridden

Explicitly calling superclass method

Polymorphism

The ability of an object to take on many forms.

 

Most common use of polymorphism in OOP is when parent class is used to refer to a child class object. (as a Polymorphic argument)

 

Subclass of that supertype can be substituted where the supertype is expected.

  • Code becomes more cleaner and more flexible
  • More efficient and simpler code
  • Can write code that does not have to change when we introduce new subclass types

Polymorphism

Cat tom = new Cat()

Usual way of declaring a reference variable

Animal tom = new Cat()

Superclass of Cat

Reference Variable

Reference type can be a superclass of the actual created object, while preserving overriden methods

Polymorphism Demo (Classes)

class Animal{
  String name;
  public String makeNoise(){
    return "";
  }

  public Animal(String name){
    this.name = name;
    System.out.println("A new animal instance is created!");
  }
}

class Cat extends Animal {
  public Cat(String name){
    super(name);
  }
  public String makeNoise(){
    return "Meooowww";
  }
}

class Dog extends Animal{
  public Dog (String name){
    super(name);
  }
  public String makeNoise(){
    return "WoOF ! WoOF!";
  }
}

class Cow extends Animal{
  public Cow(String name){
    super(name);
  }
  public String makeNoise(){
    return "MoooOOOoOOoo";
  }
}

Polymorphism Demo (Main)

public class PolymorphismDemo{
  public static void main(String[] args){
    Animal tom = new Cat("Tom");
    Animal rusty = new Dog("Rusty");
    Animal billy = new Cow("Billy");

    System.out.println(tom.makeNoise());
    System.out.println(rusty.makeNoise());
    System.out.println(billy.makeNoise());

  }

}

Overridden methods are preserved

Polymorphic Array

public class PolymorphicArray{
  public static void main(String[] args){

    Animal[] animals = new Animal[5];
    animals[0] = new Cat("Tom");
    animals[1] = new Cat("Jerry");
    animals[2] = new Dog("Rusty");
    animals[3] = new Dog("Courage");
    animals[4] = new Cow("Billy");

    for(int i =0; i < animals.length; i++){
      System.out.println(animals[i].makeNoise());
    }
  }
}

Polymorphic Method Arguments

class Vet {
  public String giveInjection(Animal a){
    return(a.makeNoise());
  }
}

public class PolymorphicArgs{
  public static void main(String[] args){
    Vet abu = new Vet();

    Dog rusty = new Dog("Rusty");
    Cat tom = new Cat("Tom");

    System.out.println(abu.giveInjection(rusty));
    System.out.println(abu.giveInjection(tom));

  }
}

Function is able to take ANY animal type as parameter. 

 

Addition of more subclasses in the future will not affect this code

Abstraction

  • Process of hiding the implementation details from the user
  • Only the functionality will be provided to the user. User will have information on WHAT the object does, and not HOW it does
  • Not to be confused with encapsulation
  • Implemented using Abstract Classes and Interfaces
  • Sending email example

Abstract Classes

  • May or may not contain abstract method (methods without body)
  • But if a class contains at least one abstract method, it MUST be declared abstract
  • Cannot be instantiated
  • Abstract class is inherited, with its abstract methods implemented and overridden
  • If inherited, MUST override all its abstract methods
  • Some classes are not meant to be instantiated.
    • Eg Animal class. What is an animal?
  • but we need the class for inheritance and polymorphism
  • We want programmers to instantiate only subclasses of animals, but not the Animal itself
  • Provide common protocols to all classes inheriting the abstract class

Abstract Superclass

Cat

move()
makeNoise()

Animal

name
age
breed

Cow

move()
makeNoise()

move()
makeNoise()

sleep()

Dog

move()
makeNoise()

Abstract Animal Class

Subclass

Stripe

Color

abstract methods; must be overridden

Abstraction Demo (classes)

abstract class Animal {
  String name;
  String breed;

  public Animal(String name, String breed){
    this.name = name;
    this.breed = breed;
  }
  public abstract String move(); //abstract method
  public void sayHi(){
    System.out.println("Hi, my name is " + name + "!");
  }
}

class Cat extends Animal {
  public Cat(String name, String breed){
    super(name, breed);
  }
  public String move(){
    return "Wallkinggg!";
  }
}

Declaring abstract method

Abstract method has no body

MUST override an abstract method. Otherwise...

Abstraction Demo (Main)

public class AbstractDemo{
  public static void main(String[] args){
    // Animal a = new Animal("Tom", "Russian Blue");
    Animal a = new Cat("Tom", "Russian Blue");
    Cat m = new Cat("Miky", "Russian Blue");
    a.sayHi();
    m.sayHi();
  }
}

CANNOT instantiate an abstract class

Interfaces

Cat

move()
makeNoise()

Animal

name
age
breed

Cow

move()
makeNoise()

move()
makeNoise()

sleep()

Dog

move()
makeNoise()

Superclass

Subclass

  • Lets say we want to further 'classify' these animals as Pets
  • Pet has methods play() and befriendly()
  • Cat and Dog are pets. Cows normally are not pets

Stripe

Color

Interfaces

Cat

move()
makeNoise()

play()

beFriendly()

Animal

Cow

move()
makeNoise()

Dog

move()
makeNoise()

Play()

beFriendly()

  • Cannot implement Pet methods in superclass because not all animals are pets

Stripe

Color

Codes are still repeated.

  • Modifying 1 Play() method will need to modify all Play() methods. What if we missed out 1?
  • What if Pets now have new method takeAWalk() ?
  • Not a good design
  • You also wont define protocols for the Pet contract.
  • Wont get to apply polymorphism for Pet methods

Solution: Implementing an Interface

Cat

move()
makeNoise()

Animal

name
age
breed

Cow

move()
makeNoise()

move()
makeNoise()

sleep()

Dog

move()
makeNoise()

Superclass

Stripe

Color

Pet

play()

beFriendly()

takeAWalk()

Interface

  • 100% pure abstract class
  • ALL methods are abstract (MUST be overridden)

Interface Demo (Classes)

abstract class Animal {
  String name;
  String breed;

  public Animal(String name, String breed){
    this.name = name;
    this.breed = breed;
  }
  public abstract String move(); //abstract method
  public void sayHi(){
    System.out.println("Hi, my name is " + name + "!");
  }
}

interface Pet {
  public abstract void beFriendly();
  public abstract void takeAWalk();
}

class Cat extends Animal implements Pet {
  public Cat(String name, String breed){
    super(name, breed);
  }
  public String move(){
    return "Wallkinggg!";
  }
  public void beFriendly(){
    System.out.println("La la la la Feed me some fish!");
  }
  public void takeAWalk(){
    System.out.println("hmm I love walking with my Cat master!");
  }
}

class Dog extends Animal implements Pet{
  public Dog (String name, String breed){
    super(name, breed);
  }
  public String move(){
    return "Runn run runnnnn!";
  }
  public String makeNoise(){
    return "WoOF ! WoOF!";
  }
  public void beFriendly(){
    System.out.println("La la la la Feed me dog food!");
  }
  public void takeAWalk(){
    System.out.println("hmm I love walking with my Dog master!");
  }
}

class Cow extends Animal{
  public Cow(String name, String breed){
    super(name, breed);
  }
  public String move(){
    return "Walkingggg veryyy slowwwlyyy...";
  }
  public String makeNoise(){
    return "MoooOOOoOOoo";
  }
}

Interface Demo (Main)

public class InterfaceDemo{
  public static void main(String[] args){
    Cat tom = new Cat("Tom", "Russian Blue" );
    // Animal rusty = new Dog("Rusty", "German Shepherd");
    // wont run becuase not all animals are pets
    Dog rusty = new Dog("Rusty", "German Shepherd");

    tom.beFriendly();
    tom.takeAWalk();
    rusty.beFriendly();
    rusty.takeAWalk();

  }
}

Animal rusty = new Dog("Rusty', "German Shepherd");

 

Would not work because:

  • Not all animals are pets
  • Animal superclass does not contain Pet methods

Recap

  1. Understanding Programming Paradigms
  2. Object Oriented Programming: What and Why?
    • Conceptual definitions
    • Comparison against Procedural programming
  3. OOP Design Principles
    • Encapsulation
    • Inheritance
    • Polymorphism
    • Abstraction and Interfaces
  4. Quiz

KAHOOT!

The End

Now its time for...

References

  • O'Reilly Head First Java Book 2nd Edition
  • http://cs.lmu.edu/~ray/notes/paradigms/
  • https://en.wikipedia.org/wiki/Programming_paradigm
  • https://www.tutorialspoint.com/java/java_object_classes.htm
  • https://medium.freecodecamp.org/object-oriented-programming-concepts-21bb035f7260
  • http://www.introprogramming.info/english-intro-csharp-book/read-online/chapter-20-object-oriented-programming-principles/#_Toc362296568
  • http://www.ntu.edu.sg/home/ehchua/programming/java/J3a_OOPBasics.html
  • http://codebetter.com/raymondlewallen/2005/07/19/4-major-principles-of-object-oriented-programming/
  • https://www.tutorialspoint.com/cplusplus/cpp_object_oriented.htm
  • http://www.ctp.bilkent.edu.tr/~russell/java/LectureNotes/1_OOConcepts.htm

OOP Concepts

By Asyrul Hafetzy

OOP Concepts

  • 314