Java Object-Oriented Programming II

Introduction

Java Object-Oriented Programming II

Contents

  1. Composition in Java
  2. Inheritance in Java
  3. Encapsulation in Java
  4. Polymorphism in Java

The basic principles of OOP involves Abstraction, Encapsulation, Inheritance, and Polymorphism

1. Composition in Java

A composition in Java between two objects associated with each other exists when there is a strong relationship between one class and another.

Composition is deal with has relationship.

package anote;

public class Main {
    public static void main(String[] args) {
        Dimensions dimensions = new Dimensions(20, 20, 7);
        Case theCase = new Case("220B", "Samsung", "240", dimensions);
        Monitor theMonitor = new Monitor("27inch ", "LG", 27, new Resolution(2540, 1440));
        Motherboard theMotherboard = new Motherboard("BJ-200", "Samsung", 4, 6, "v2.44");

        PC thePC = new PC(theCase, theMonitor, theMotherboard);
        thePC.powerUp();
        // So, the PC has a monitor, a motherboard, and a case.
    }
}

class PC {

    private Case theCase;
    private Monitor monitor;
    private Motherboard motherboard;

    public PC(Case theCase, Monitor monitor, Motherboard motherboard) {
        this.theCase = theCase;
        this.monitor = monitor;
        this.motherboard = motherboard;
    }

    public void powerUp() {
        theCase.pressPowerButton();
        drawLogo();
    }

    private void drawLogo() {
        monitor.drawPixelAt(1000, 50, "red");
    }
}

class Monitor {
    // Monitor has a Resolution
    private String model;
    private String manufacturer;
    private int size;
    private Resolution nativaResolution;

    public String getModel() {
        return this.model;
    }

    public String getManufacturer() {
        return this.manufacturer;
    }

    public int getSize() {
        return this.size;
    }

    public Resolution getNativaResolution() {
        return this.nativaResolution;
    }

    public Monitor(String model, String manufacturer, int size, Resolution nativaResolution) {
        this.model = model;
        this.manufacturer = manufacturer;
        this.size = size;
        this.nativaResolution = nativaResolution;
    }

    public void drawPixelAt(int x, int y, String color) {
        System.out.println("Drawing pixel at " + x + "," + y + " in color " + color);
    }
}

class Motherboard {
    private String model;
    private String manufacturer;
    private int ramSlots;
    private int cardSlots;
    private String bios;

    public void loadProgram(String programName) {
        System.out.println("Program " + programName + " is now loading...");
    }

    public String getModel() {
        return this.model;
    }

    public String getManufacturer() {
        return this.manufacturer;
    }

    public int getRamSlots() {
        return this.ramSlots;
    }

    public int getCardSlots() {
        return this.cardSlots;
    }

    public String getBios() {
        return this.bios;
    }

    public Motherboard(String model, String manufacturer, int ramSlots, int cardSlots, String bios) {
        this.model = model;
        this.manufacturer = manufacturer;
        this.ramSlots = ramSlots;
        this.cardSlots = cardSlots;
        this.bios = bios;
    }
}

class Case {
    // Case has a dimensions
    private String model;
    private String manufacturer;
    private String powerSupply;
    private Dimensions dimensions;

    public Case(String model, String manufacturer, String powerSupply, Dimensions dimensions) {
        this.model = model;
        this.manufacturer = manufacturer;
        this.powerSupply = powerSupply;
        this.dimensions = dimensions;
    }

    public void pressPowerButton() {
        System.out.println("Power button pressed");
    }

    public String getModel() {
        return model;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public String getPowerSupply() {
        return powerSupply;
    }

    public Dimensions getDimensions() {
        return dimensions;
    }

}

class Dimensions {

    private int width;
    private int height;
    private int depth;

    public Dimensions(int width, int height, int depth) {
        this.width = width;
        this.height = height;
        this.depth = depth;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public int getDepth() {
        return depth;
    }
}

class Resolution {

    private int width;
    private int height;

    public int getWidth() {
        return this.width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return this.height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public Resolution(int width, int height) {
        this.width = width;
        this.height = height;
    }
}
Power button pressed
Drawing pixel at 1000,50 in color red

2. Inheritance in Java

Java as an Object-Oriented Program language really allows us to do is to create classes to inherit commonly used states and behavior (fields and methods) from other classes.

Base Class: The class whose features are inherited is known as a base class(or a super class or a parent class).

Extended class The class that inherits the other class is known as an extended class(a derived class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.

Base Class

sample/People.java

package sample;

public class People {
    private String name;
    private int age;

    public People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String move() {
        return this.name + " is moving";
    }

    /**
     * @return String return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @return int return the age
     */
    public int getAge() {
        return age;
    }
}
  • Created people constructor with name and age parameters.

Extended class

sample/American.java

package sample;

public class American extends People {

    private String language;
    private String conutry;

    public American(String name, int age, String language, String conutry) {
        super(name, age);
        this.language = language;
        this.conutry = conutry;
    }

    public String speak() {
        return this.getName() + " can speak " + this.language;
    }

    @Override
    public String move() {
        return this.getName() + " is moving in "+ this.conutry;
    }

    /**
     * @return String return the language
     */
    public String getLanguage() {
        return language;
    }

    /**
     * @return String return the conutry
     */
    public String getConutry() {
        return conutry;
    }
}
  • speak() method is a unique method for American Class
  • with extends keywords American class can access People class’s methods and fields.

Main Class

sample/Main.java

package sample;

public class Main {
    public static void main(String[] args) {
        
        People tim = new People("Tim", 45);
        American mike = new American("Mike", 23, "English", "conutry");
        
        // From Base Class 
        System.out.println(mike.getName());
        System.out.println(mike.getAge());
        System.out.println(mike.move());

        // From American Class
        System.out.println(mike.getLanguage());
        System.out.println(mike.getConutry());
        System.out.println(mike.speak());

    }
}
Mike
23
Mike is moving in conutry
English
conutry
Mike can speak English

This means American class can use Methods and fields in People class which is base class by extends keyword.

@Override annotation

@Override
public String move() {
    return this.getName() + " is moving in "+ this.conutry;
}

@Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance.

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

3. Encapsulation in Java

In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object’s components.

Why we are using Encapsulation?

  • You are able to protect the members of a class from external access in order to really guard against unauthorized access.

With Encapsulation

package anote;

class Player {
    private String name;
    private int health = 100;
    private String weapon;

    public Player(String name, int health, String weapon) {
        this.name = name;

        if (health > 0 && health <= 100) {
            this.health = health;
        }
        this.weapon = weapon;
    }

    public void loseHealth(int damage) {
        this.health = this.health - damage;

        if (this.health <= 0) {
            System.out.println("Player knocked out");
        }
    }

    public int getHealth() {
        return health;
    }

}

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

        Player player = new Player("Tim", 200, "Sword");
        System.out.println("Initial health is " + player.getHealth());

    }
}
Initial health is 100

Without Encapsulation

The problem without Encapsulation

  • We have got the ability to change the player’s fields directly.
package anote;

class Player {
    public String name;
    public int health;
    public String weapon;

    public void loseHealth(int damage) {
        this.health = this.health - damage;

        if (this.health <= 0) {
            System.out.println("Player knocked out");
        }
    }

    public int healthRemaining() {
        return this.health;
    }
}

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

        Player player = new Player();
        player.name = "Tim";
        player.health = 20;
        player.weapon = "Sword";

        int damage = 10;
        player.loseHealth(damage);
        System.out.println("Remaining health = " + player.healthRemaining());

        damage = 11;

        player.loseHealth(damage);
        System.out.println("Remaining health = " + player.healthRemaining());
    }
}
Remaining health = 10
Player knocked out
Remaining health = -1

4. Polymorphism in Java

In Java, polymorphism refers to the ability of a class to provide different implementations of a method, depending on the type of object that is passed to the method.

If you are inheriting from another class, and you have got a method, and you override that method, that is what polymorphism

package anote;

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

        for (int i=1; i<6; i++){
            Movie movie = randomMovie();
            System.out.println("Movie #" + ":" + movie.getName() + "\n" + "Plot: " + movie.plot() + "\n" );
        }
    }

    public static Movie randomMovie(){
        int randomNumber = (int) (Math.random() * 3) + 1;
        System.out.println("Random number generated was: " + randomNumber);
        switch(randomNumber){
            case 1:
                return new Jaws();
            case 2:
                return new LoveLetter();
            case 3:
                return new DoctorStrange();
        }
        return null;
    }
}

class Movie {
    private String name;

    public Movie(String name) {
        this.name = name;
    }

    public String plot() {
        return "No plot here";
    }

    public String getName(){
        return name;
    }
}

class Jaws extends Movie {
    public Jaws() {
        super("Jaws");
    }

    public String plot() {
        return "A shark eats lots of people";
    }
}

class LoveLetter extends Movie {
    public LoveLetter() {
        super("Love Letter");
    }

    @Override
    public String plot() {
        return "Hello, How are you";
    }
}

class DoctorStrange extends Movie {
    public DoctorStrange() {
        super("Doctor Strange");
    }
    // No plot
}
Random number generated was: 3
Movie #:Doctor Strange
Plot: No plot here

Random number generated was: 1
Movie #:Jaws
Plot: A shark eats lots of people

Random number generated was: 2
Movie #:Love Letter
Plot: Hello, How are you

Random number generated was: 3
Movie #:Doctor Strange
Plot: No plot here

Random number generated was: 2
Movie #:Love Letter
Plot: Hello, How are you

Leave a Reply

Your email address will not be published.

ANOTE.DEV