Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
32 kB
3
Indexable
Never
javacore.organization.oop.classhierarchies

1. abstraction
    1.1. demo
        1.1.1. Demo

//truu tuong hoa du lieu la qua trinh an di mot so chi tiet nhat dinh va chi hien thi thong can thiet cho nguoi dung
//lop truu tuong khong the duoc dung de tao ra cac doi tuong nhu cac lop binh thuong khac

//Abstract class
abstract class Animal{
	//Abstract method
	public abstract void animalSound();
	
	public void sleep(){
		System.out.println("zzz");
	}
}

class Pig extends Animal{
	public void animalSound(){
		System.out.println("The pig says: wee wee");
	}
}

class Diem extends Hinh{
	public Diem(ToaDo toaDo) {
		super(toaDo);
	}

	@Override
	public double tinhDienTich() {
		// TODO Auto-generated method stub
		return 1;
	}
}

class HinhTron extends Hinh{
	private double r;
	public HinhTron(ToaDo toaDo, double r) {
		super(toaDo);
		this.r = r;
	}
	public double getR() {
		return r;
	}
	public void setR(double r) {
		this.r = r;
	}
	@Override
	public double tinhDienTich() {
		// TODO Auto-generated method stub
		return Math.PI*r*r;
	}
}

class HinhChuNhat extends Hinh{
	private int chieuRong, chieuDai;

	public HinhChuNhat(ToaDo toaDo, int chieuRong, int chieuDai) {
		super(toaDo);
		this.chieuRong = chieuRong;
		this.chieuDai = chieuDai;
	}

	@Override
	public double tinhDienTich() {
		// TODO Auto-generated method stub
		return chieuRong * chieuDai;
	}	
}

public class Demo {
	public static void main(String[] args) {
		Pig myPig = new Pig();
		myPig.animalSound();
		myPig.sleep();
		
		ToaDo td1 = new ToaDo(5,5);
		ToaDo td2 = new ToaDo(7,9);
		ToaDo td3 = new ToaDo(8,1);
		
		Hinh h1 = new Diem(td1);
		Hinh h2 = new HinhTron(td2, 2);
		Hinh h3 = new HinhChuNhat(td3, 3 , 5);
		
		System.out.println(h1.tinhDienTich());
		System.out.println(h2.tinhDienTich());
		System.out.println(h3.tinhDienTich());
	}
}

#######################

        1.1.2. Hinh

public abstract class Hinh {
	protected ToaDo toaDo;

	public Hinh(ToaDo toaDo) {
		this.toaDo = toaDo;
	}

	public ToaDo getToaDo() {
		return toaDo;
	}

	public void setToaDo(ToaDo toaDo) {
		this.toaDo = toaDo;
	}
	
	public abstract double tinhDienTich();
}

##################################

        1.1.3. ToaDo

public class ToaDo {
	int x, y;

	public ToaDo(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}
	
}

#######################################

    1.2. example
        1.2.1. Animal

abstract class Animal {
    private String name;

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

    public abstract void eat();

    public abstract void breathe();

    public String getName() {
        return name;
    }
}

#######################################

        1.2.2. Bird

abstract class Bird extends Animal implements CanFly{

    public Bird(String name) {
        super(name);
    }

    @Override
    public void eat() {
        System.out.println(getName() + " is pecking");
    }

    @Override
    public void breathe() {
        System.out.println("Breathe in, breathe out, repeat");
    }

    @Override
    public void fly() {
        System.out.println(getName() + " is flapping its wings");
    }
}

#########################################

        1.2.3. CanFly

public interface CanFly {
    void fly();
}

########################################

        1.2.4. Dog

class Dog extends Animal {

    public Dog(String name) {
        super(name);
    }

    @Override
    public void eat() {
        System.out.println(getName() + " is eating");
    }

    @Override
    public void breathe() {
        System.out.println("Breathe in, breathe out, repeat");
    }
}

##########################################

        1.2.5. Main

/*
 * Abstract class va Interface deu khong the duoc khoi tao, va chung co the chua ca method duoc khai bao ma co hoac khong
 * co trien khai
 *
 * Trong Abstract class co the khai bao cac truong khong phai static hoac final, va xac dinh public, protected, private
 * methods
 * Mot Abstract class chi co the ke thua tu mot lop cha nhung co the implement nhieu interfaces
 */

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog("Yorkie");
        dog.breathe();
        dog.eat();

        Bird bird = new Parrot("Parrot");
        bird.breathe();
        bird.eat();
        bird.fly();

        Parrot parrot = new Parrot("Australia ringnec");
        parrot.breathe();
        parrot.eat();
        parrot.fly();

        Penguin penguin = new Penguin("Emperor");
        penguin.fly();
    }
}

##############################################

        1.2.6. Parrot

public class Parrot extends Bird{

    public Parrot(String name) {
        super(name);
    }

    @Override
    public void fly() {
        System.out.println("Flitting from branch to branch");
    }
}

###########################################

        1.2.7. Penguin

public class Penguin extends Bird{
    public Penguin(String name) {
        super(name);
    }

    @Override
    public void fly() {
        super.fly();
        System.out.println("I'm not very good at that, can I go for a swim instead?");
    }
}

###########################################

    1.3. AbstractClassVsInterface

public class AbstractClassVsInterface {
    /*
    Below you can see a list of some important differences between these two concepts:

    an abstract class can have abstract and non-abstract instance methods while an interface can have abstract or default instance methods;

    an abstract class can extend another abstract or regular class and an interface can only extend another interface;

    an abstract class can extend only one class while an interface can extend any number of interfaces;

    an abstract class can have final, non-final, static, non-static variables (regular fields) while an interface can only have static final variables;

    an abstract class can provide an implementation of an interface but an interface cannot provide an implementation of an abstract class;

    an abstract class can have a constructor and an interface cannot;

    in an abstract class, the keyword abstract is mandatory to declare a method as an abstract one while in an interface this keyword is optional.
     */
}

// Using abstract classes and interfaces together
interface ManagedDevice {

    void on();

    void off();
}

abstract class AbstractDevice implements ManagedDevice {

    protected String serialNumber;
    protected boolean on;

    public AbstractDevice(String serialNumber) {
        this.serialNumber = serialNumber;
    }

    protected void setOn(boolean on) {
        this.on = on;
    }
}

class Kettle extends AbstractDevice {

    protected double volume;

    public Kettle(String serialNumber, double volume) {
        super(serialNumber);
        this.volume = volume;
    }

    @Override
    public void on() {
        // do complex logic to activate all electronic components
        setOn(true);
    }

    @Override
    public void off() {
        // do complex logic to stop all electronic components
        setOn(false);
    }
}

########################################

2. encapsulation
    2.1. Demo

/*
 * Tinh dong goi (Enscapsulation): dam bao du lieu nhay cam duoc an khoi nguoi dung -> khai bao thuoc tinh la rieng tu va cung cap cac phuong thuc get va set cong khai de truy cap va cap nhat gia tri cua bien rieng tu
 * Che giau di mot so du lieu, ham, phuong thuc de da bao cac du lieu do duoc su dung dung cach
 */

public class Demo {
	public class Person{
		private String name;
		
		//getter
		public String getName(){
			return name;
		}
		
		//setter
		public void setName(String newName){
			this.name = newName; //this de chi doi tuong hien tai
		}
	}
}

#########################################

    2.2. Main

public class Main {
    public static void main(String[] args) {
        Player player = new Player();
        player.name = "Thieu";
        player.health = 100;
        player.weapon = "Sword";

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

        EnhancedPlayer enhancedPlayer = new EnhancedPlayer("Thieu", 50, "Sword");
        System.out.println("Initial health of enhanced player is " + enhancedPlayer.getHealth());
    }
}

class EnhancedPlayer {
    private String name;
    private int hitPoints = 100;
    private String weapon;

    public EnhancedPlayer(String name, int health, String weapon) {
        this.name = name;
        if (health > 0 && health <= 200) {
            this.hitPoints = health;
        }
        this.weapon = weapon;
    }

    public void loseHealth(int damage) {
        this.hitPoints -= damage;
        if (hitPoints <= 0) {
            System.out.println("Player knocked out");
        }
    }

    public int getHealth() {
        return hitPoints;
    }
}

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

    public void loseHealth(int damage) {
        this.health -= damage;
        if (health <= 0) {
            System.out.println("Player knocked out");
        }
    }

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

##########################################

3. inheritance
    3.1. Demo

//Subclass and Superclass

//Neu khong muon class khac ke thua class hien tai thi dung tu khoa final o truoc class hien tai

//Trong Java khong co da ke thua
//Ke thua bieu dien moi quan he giua hai lop cha - con (IS-A relationship)

public class Demo {
	public static class Human{
		protected String name;
		protected int yearOfBirth;
		
		public Human(String name, int yearOfBirth) {
			this.name = name;
			this.yearOfBirth = yearOfBirth;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getYearOfBirth() {
			return yearOfBirth;
		}

		public void setYearOfBirth(int yearOfBirth) {
			this.yearOfBirth = yearOfBirth;
		}
		
		public void eat(){
			System.out.println("yummy");
		}
		
		public void drink(){
			System.out.println("uwu");
		}
		
		public void sleep(){
			System.out.println("hmhm");
		}
	}
	
	public static class Student extends Human {
		private String className;
		private String shoolName;
		
		public Student(String name, int yearOfBirth, String className, String shoolName) {
			super(name, yearOfBirth);
			this.className = className;
			this.shoolName = shoolName;
		}

		public String getClassName() {
			return className;
		}

		public void setClassName(String className) {
			this.className = className;
		}

		public String getShoolName() {
			return shoolName;
		}

		public void setShoolName(String shoolName) {
			this.shoolName = shoolName;
		}

		public void doHomework(){
			System.out.println("Done!");
		}
	}
	
	public static void main(String[] args) {
		Human cn = new Human("Thieu", 1999);
		cn.eat();
		cn.drink();
		cn.sleep();
		
		Student hs = new Student("Thieu", 1999, "Lop 17", "SRV");
		hs.eat();
		hs.drink();
		hs.sleep();
		hs.doHomework();
	}
}

##########################################

    3.2. Main

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal("Animal", 1, 1, 5, 5);

        Dog dog = new Dog("Yorkie", 8, 20, 2, 4, 1, 20, "long silky");
        dog.eat();
        System.out.println(dog.getSize());
    }
}

class Animal {

    private String name;
    private int brain;
    private int body;
    private int size;
    private int weight;

    public Animal(String name, int brain, int body, int size, int weight) {
        this.name = name;
        this.brain = brain;
        this.body = body;
        this.size = size;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public int getBrain() {
        return brain;
    }

    public int getBody() {
        return body;
    }

    public int getSize() {
        return size;
    }

    public int getWeight() {
        return weight;
    }

    public void eat() {
        System.out.println("Animal eat");
    }

    public void move() {
        System.out.println("Animal move");
    }
}

class Dog extends Animal {

    private int eyes;
    private int legs;
    private int tail;
    private int teeth;
    private String coat;

    public Dog(String name, int size, int weight, int eyes, int legs, int tail, int teeth, String coat) {
        super(name, 1, 1, size, weight);
        this.eyes = eyes;
        this.legs = legs;
        this.tail = tail;
        this.teeth = teeth;
        this.coat = coat;
    }

    @Override
    public void eat() {
        System.out.println("Dog eat");
    }

    @Override
    public void move() {
        super.move();
    }

    public void chew() {
        System.out.println("Dog chew");
    }
}

#######################################

4. interfaces
    4.1. demo
        4.1.1. Demo

//Mot interface la mot "ban thiet ke" cua mot lop - la mot abstract class -> chi chua hang so va phuong thuc truu tuong
//Muc dich: de dat duoc tinh truu tuong hoan toan va da ke thua trong java

interface MayTinhBoTui{
	public abstract double cong(double a, double b); //tu abstract co hay khong deu duoc
	public double tru(double a, double b);
	public double nhan(double a, double b);
	public double chia(double a, double b);
}

class MayTinhCasioFX500 implements MayTinhBoTui{

	@Override
	public double cong(double a, double b) {
		// TODO Auto-generated method stub
		return a+b;
	}

	@Override
	public double tru(double a, double b) {
		// TODO Auto-generated method stub
		return a-b;
	}

	@Override
	public double nhan(double a, double b) {
		// TODO Auto-generated method stub
		return a*b;
	}

	@Override
	public double chia(double a, double b) {
		// TODO Auto-generated method stub
		return a/b;
	}
	
}

class MayTinhVinacal500 implements MayTinhBoTui{

	@Override
	public double cong(double a, double b) {
		// TODO Auto-generated method stub
		return a+b;
	}

	@Override
	public double tru(double a, double b) {
		// TODO Auto-generated method stub
		return a-b;
	}

	@Override
	public double nhan(double a, double b) {
		// TODO Auto-generated method stub
		return a*b;
	}

	@Override
	public double chia(double a, double b) {
		// TODO Auto-generated method stub
		return a/b;
	}
	
}

interface SapXepInterface{
	public void sapXepTang(double[] arr);
	public void sapXepGiam(double[] arr);
}

class SapXepChen implements SapXepInterface{

	@Override
	public void sapXepTang(double[] arr) {
		// TODO Auto-generated method stub
		int i, j;
		double key;
		int n = arr.length;
		for(i = 1; i < n; i++){
			key = arr[i];
			j = i - 1;
			while(j >= 0 && arr[j] > key){
				arr[j+1] = arr[j];
				j = j - 1;
			}
			arr[j+1] = key;
		}
	}

	@Override
	public void sapXepGiam(double[] arr) {
		// TODO Auto-generated method stub
		int i, j;
		double key;
		int n = arr.length;
		for(i = 1; i < n; i++){
			key = arr[i];
			j = i - 1;
			while(j >= 0 && arr[j] < key){
				arr[j+1] = arr[j];
				j = j - 1;
			}
			arr[j+1] = key;
		}
	}
	
}

class SapXepChon implements SapXepInterface{

	@Override
	public void sapXepTang(double[] arr) {
		// TODO Auto-generated method stub
		int i, j, minIndex;
		int n = arr.length;
		for(i = 0; i < n - 1; i++){
			minIndex = i;
			for(j = i + 1; j < n; j++){
				if(arr[j] < arr[minIndex]) minIndex = j;
			}
			double tmp = arr[i];
			arr[i] = arr[minIndex];
			arr[minIndex] = tmp;
		}
	}

	@Override
	public void sapXepGiam(double[] arr) {
		// TODO Auto-generated method stub
		int i, j, maxIndex;
		int n = arr.length;
		for(i = 0; i < n - 1; i++){
			maxIndex = i;
			for(j = i + 1; j < n; j++){
				if(arr[j] > arr[maxIndex]) maxIndex = j;
			}
			double tmp = arr[i];
			arr[i] = arr[maxIndex];
			arr[maxIndex] = tmp;
		}
	}

}

class PhanMemMayTInh implements MayTinhBoTui, SapXepInterface{

	@Override
	public double cong(double a, double b) {
		// TODO Auto-generated method stub
		return a+b;
	}

	@Override
	public double tru(double a, double b) {
		// TODO Auto-generated method stub
		return a-b;
	}

	@Override
	public double nhan(double a, double b) {
		// TODO Auto-generated method stub
		return a*b;
	}

	@Override
	public double chia(double a, double b) {
		// TODO Auto-generated method stub
		return a/b;
	}
	
	@Override
	public void sapXepTang(double[] arr) {
		// TODO Auto-generated method stub
		int i, j;
		double key;
		int n = arr.length;
		for(i = 1; i < n; i++){
			key = arr[i];
			j = i - 1;
			while(j >= 0 && arr[j] > key){
				arr[j+1] = arr[j];
				j = j - 1;
			}
			arr[j+1] = key;
		}
	}

	@Override
	public void sapXepGiam(double[] arr) {
		// TODO Auto-generated method stub
		int i, j;
		double key;
		int n = arr.length;
		for(i = 1; i < n; i++){
			key = arr[i];
			j = i - 1;
			while(j >= 0 && arr[j] < key){
				arr[j+1] = arr[j];
				j = j - 1;
			}
			arr[j+1] = key;
		}
	}
	
}

public class Demo {
	public static void main(String[] args) {
		System.out.println("Test cau a: ");
		MayTinhCasioFX500 mfx500 = new MayTinhCasioFX500();
		MayTinhVinacal500 mvn500 = new MayTinhVinacal500();
	
		System.out.println("5+3 = " + mfx500.cong(5,3));
		System.out.println("4x5 = " + mvn500.nhan(4,5));
		
		System.out.println("Test cau b: ");
		double[] arr1 = new double[] {5,1,3,4,8,0,5};
		double[] arr2 = new double[] {6,7,2,9,2,4,5};
		SapXepChen sxc = new SapXepChen();
		SapXepChon sxchon = new SapXepChon();
		
		sxc.sapXepTang(arr1);
		sxchon.sapXepGiam(arr2);
		for(double i : arr1){
			System.out.print(i + " ");
		}
		System.out.println();
		for(double i : arr2){
			System.out.print(i + " ");
		}
		System.out.println();
	
		
		System.out.println("Test cau c: ");
		PhanMemMayTInh pmmt = new PhanMemMayTInh();
		System.out.println("3+5 = " + pmmt.cong(3, 5));
		double[] arr3 = new double[] {6,7,2,9,2,4,5};
		pmmt.sapXepTang(arr3);
		for(double i : arr3){
			System.out.print(i + " ");
		}
		System.out.println();
		
	}
}

##################################################

        4.1.2. ITelephone

public interface ITelephone {
    void powerOn();
    void dial(int phoneNumber);
    void answer();
    boolean callPhone(int phoneNumber);
    boolean isRinging();
}

##################################################

        4.1.3. Main

class Gearbox {
    private boolean clutchIsIn;

    public void  operateClutch(String inOrOut) {
        this.clutchIsIn = inOrOut.equalsIgnoreCase("in");
    }
}

class DeskPhone implements ITelephone {
    private int myNumber;
    private boolean isRinging;

    public DeskPhone(int myNumber) {
        this.myNumber = myNumber;
    }

    @Override
    public void powerOn() {
        System.out.println("No action taken, desk phone does not have a power button");
    }

    @Override
    public void dial(int phoneNumber) {
        System.out.println("Now ringing " + phoneNumber + " on desk phone");
    }

    @Override
    public void answer() {
        if (isRinging) {
            System.out.println("Answering the desk phone");
            isRinging = false;
        }
    }

    @Override
    public boolean callPhone(int phoneNumber) {
        if (phoneNumber == myNumber) {
            isRinging = true;
            System.out.println("Ring ring");
        } else {
            isRinging = false;
        }

        return isRinging;
    }

    @Override
    public boolean isRinging() {
        return isRinging;
    }

    public void abc() {
        System.out.println("HEHE");
    }
}

class MobilePhone implements ITelephone {
    private int myNumber;
    private boolean isRinging;
    private boolean isOn = false;

    public MobilePhone(int myNumber) {
        this.myNumber = myNumber;
    }

    @Override
    public void powerOn() {
        isOn = true;
        System.out.println("Mobile phone powered up");
    }

    @Override
    public void dial(int phoneNumber) {
        if (isOn) {
            System.out.println("Now ringing " + phoneNumber + " on mobile phone");
        } else {
            System.out.println("Phone is switched off");
        }
    }

    @Override
    public void answer() {
        if (isRinging) {
            System.out.println("Answering the mobile phone");
            isRinging = false;
        }
    }

    @Override
    public boolean callPhone(int phoneNumber) {
        if (phoneNumber == myNumber && isOn) {
            isRinging = true;
            System.out.println("Melody ring");
        } else {
            isRinging = false;
            System.out.println("Mobile phone not on or number different");
        }

        return isRinging;
    }

    @Override
    public boolean isRinging() {
        return isRinging;
    }
}

public class Main {
    public static void main(String[] args) {
        ITelephone timsPhone = new DeskPhone(123456);
        timsPhone.powerOn();
        timsPhone.callPhone(123456);
        timsPhone.answer();

        timsPhone = new MobilePhone(654321);
        timsPhone.powerOn();
        timsPhone.callPhone(654321);
        timsPhone.answer();
    }
}

##############################################

    4.2. DeclaringFunctionality

interface MyInterface {
    int INT_CONSTANT = 0; // it's a constant, the same as public static final int INT_CONSTANT = 0

    void instanceMethod1();

    void instanceMethod2();

    // The staticMethod() is just a regular static method.
    static void staticMethod() {
        System.out.println("Interface: static method");
    }

    // The default method defaultMethod() has an implementation, but it can be overridden in subclasses.
    default void defaultMethod() {
        System.out.println("Interface: default method. It can be overridden");
    }

    // The privateMethod has an implementation as well and can be used to decompose default methods.
    private void privateMethod() {
        System.out.println("Interface: private methods in interfaces are acceptable but should have a body");
    }
}

class MyClass implements MyInterface {

    @Override
    public void instanceMethod1() {
        System.out.println("Class: instance method1");
    }

    @Override
    public void instanceMethod2() {
        System.out.println("Class: instance method2");
    }
}

public class DeclaringFunctionality {

    public static void main(String[] args) {
        DrawingTool pencil = new Pencil();
        DrawingTool brush = new Brush();

        MyInterface instance = new MyClass();
        instance.instanceMethod1();
        instance.instanceMethod2();
        instance.defaultMethod();

        MyInterface.staticMethod();
    }
}

interface DrawingTool {
    void draw(Curve curve);
}

class Pencil implements DrawingTool {

    @Override
    public void draw(Curve curve) {

    }
}

class Brush implements DrawingTool {

    @Override
    public void draw(Curve curve) {

    }
}

class Curve { }

############################################

    4.3. DefaultFunction

/*
Default function trong interface co the duoc override hoac khong

Truong hop mot class implement hai interface deu co cung default function (cung ten) thi bat buoc phai trien khai
default function do trong class, neu khong se xay ra loi bien dich
 */

interface Feature {

    default void action() {
        System.out.println("Default action");
    }
}

class FeatureImpl implements Feature {

    @Override
    public void action() {
        System.out.println("FeatureImpl-specific action");
    }
}

public class DefaultFunction {

    public static void main(String[] args) {
        // Feature.action() // Khong the goi default function cua interface mot cach truc tiep

        new Feature() { }.action();

        Feature feature = new FeatureImpl();
        feature.action(); // FeatureImpl-specific action
    }
}

interface Movable {
    void stepAhead();
    void turnLeft();
    void turnRight();

    default void turnAround() {
        turnLeft();
        turnLeft();
    }
}

interface Jumpable {
    void jump();
    void turnLeftJump();
    void turnRightJump();
    default void turnAround() {
        turnLeftJump();
        turnLeftJump();
    }
}

class Spiderman implements Movable, Jumpable {
    // define an implementation for abstract methods
    public void stepAhead() { }
    public void turnLeft() { }
    public void turnRight() { }
    public void jump() { }
    public void turnLeftJump() { }
    public void turnRightJump() { }

    // define an implementation for conflicting default method
    @Override
    public void turnAround() {
        // define turnaround for Spiderman
        Movable.super.turnAround(); // default
    }
}

#########################################

5. overriding
    5.1. Main

class Animal{
	protected String name;

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public void eat(){
		System.out.println("eating...");
	}
	
	public void makeSound(){
		System.out.println(".........");
	}
	
	public void sleep(){
		System.out.println("zzzzzzzzz");
	}
}

class Dog extends Animal{
	public Dog(){
		super("Dog");
	}

	//@Override
	public void eat() {
		System.out.println("an xuong!");
	}

	@Override
	public void makeSound() {
		System.out.println("Go go");
	}
}

class Cat extends Animal{

	public Cat() {
		super("Cat");
	}

	//@Override
	public void eat() {
		System.out.println("an ca!");;
	}

	@Override
	public void makeSound() {
		System.out.println("meow meow");
	}
}

public class Main {
	public static void main(String[] args) {
		Dog d = new Dog();
		d.eat();
		d.makeSound();
		d.sleep();
		
		Animal an = new Cat();
		an.eat();
	}
}

#####################################################

6. polymorphism
    6.1. Demo

class Animal {
	public void animalSound() {
		System.out.println("The animal makes a sound");
	}
}

class Pig extends Animal {
	public void animalSound() {
		System.out.println("The pig says: wee wee");
	}
}

class Dog extends Animal {
	public void animalSound() {
		System.out.println("The dog says: bow wow");
	}
}

public class Demo {
	public static void main(String[] args) {
		Animal myAnimal = new Animal(); // Create a Animal object
		Animal myPig = new Pig(); // Create a Pig object
		Animal myDog = new Dog(); // Create a Dog object
		myAnimal.animalSound();
		myPig.animalSound();
		myDog.animalSound();
	}
}

####################################

    6.2. Main

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i < 11; i++) {
            Movie movie = randomMovie();
            System.out.println("Movie #" + i + " : " + movie.getName() + "\n" +
                               "Plot: " + movie.plot() + "\n");
        }
    }

    public static Movie randomMovie() {
        int randomNumber = (int) (Math.random() * 5) + 1;
        System.out.println("Random number generated was: " + randomNumber);
        return switch (randomNumber) {
            case 1 -> new Jaws();
            case 2 -> new IndependenceDay();
            case 3 -> new MazeRunner();
            case 4 -> new StarWars();
            case 5 -> new Forgetable();
            default -> 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 IndependenceDay extends Movie {

    public IndependenceDay() {
        super("Independence Day");
    }

    @Override
    public String plot() {
        return "Aliens attempt to take over planet earth";
    }
}

class MazeRunner extends Movie {

    public MazeRunner() {
        super("Maze runner");
    }

    @Override
    public String plot() {
        return "Kids try and escape a maze";
    }
}

class StarWars extends Movie {

    public StarWars() {
        super("Star wars");
    }

    @Override
    public String plot() {
        return "Imperial Forces try to take over the universe";
    }
}

class Forgetable extends Movie {

    public Forgetable() {
        super("Forgetable");
    }
}

#############################################

    6.3. Test

public class Test {
    public static void main(String[] args) {
        new TeamLead(1);
    }

    public static class TeamLead extends Programmer {

        private final int numTeamLead;

        public TeamLead(int numTeamLead) {
            super(numTeamLead);
            this.numTeamLead = numTeamLead;
            employ();
        }

        protected void employ() {
            System.out.println(numTeamLead + " teamlead");
        }

    }

    public static class Programmer {

        private final int numProgrammer;

        public Programmer(int numProgrammer) {
            this.numProgrammer = numProgrammer;
            employ();
        }

        private void employ() {
            System.out.println(numProgrammer + " programmer");
        }
    }
}

#########################################

7. RuntimeTypeChecking

/*
A variable of a base class can always refer to an object of a subclass. We can determine the actual type of the referred object at runtime.
    - the instanceof operator that can be used for testing if an object is of a specified type
    - java reflection that can be used to obtain an object representing the class.
 */

public class RuntimeTypeChecking {

    public static void main(String[] args) {
        Shape circle = new Circle();  // the reference is Shape, the object is Circle
        Shape rect = new Rectangle(); // the reference is Shape, the object is Rectangle

        boolean circleIsCircle = circle instanceof Circle; // true
        boolean circleIsRectangle = circle instanceof Rectangle; // false
        boolean circleIsShape = circle instanceof Shape; // true

        boolean rectIsRectangle = rect instanceof Rectangle; // true
        boolean rectIsCircle = rect instanceof Circle; // false
        boolean rectIsShape = rect instanceof Shape; // true

        // Pay attention, the type of the object in question should be a subtype (or the type) of the specified class.
        Circle c = new Circle();
        // boolean circleIsRect = c instanceof Rectangle; // Inconvertible types

        Shape s = new Shape();
        boolean sIsCircle = s instanceof Circle;  // false

        // Pattern matching for instanceof
        Object obj = " ";

        if (obj instanceof String str  && str.length() > 0) {
            if (str.isBlank()) {
                System.out.println("The variable is empty or contains only a whitespace");
            }
        }

        // Use reflection
        boolean equalsCircle = circle.getClass() == Circle.class; // true
        boolean equalsShape = circle.getClass() == Shape.class;   // false
        boolean rectangle = circle.getClass() == Rectangle.class; // false

        boolean isInstanceOfCircle = Circle.class.isInstance(circle); // true
        boolean isInstanceOfShape = Shape.class.isInstance(circle); // true
        boolean isInstanceOfRectangle = Rectangle.class.isInstance(circle); // false

        boolean circleIsRect = Rectangle.class.isInstance(c); // false
    }
}

class Shape {

}

class Circle extends Shape {

}

class Rectangle extends Shape {

}
Leave a Comment