SE_21_Lesson_11: Inheritance, Polymorphism

-> instanceof anlayishi, misallarla izahi 

package org.example.lesson_13;

public class Ulubaba {
public String ad;
public String soyad;
public Integer yash;

public void odunDogramaq() {
System.out.println("Ulubaba 50 kq odunu 1 saata dograyir");
}
}


package org.example.lesson_13;

public class Baba extends Ulubaba {
public String hobbi;

public void otBicmek() {
System.out.println("Baba 1 hektar otu 1 gune bicir");
}
}
package org.example.lesson_13;

public class Main {
public static void main(String[] args) {
Baba baba = new Baba();
System.out.println(baba instanceof Ulubaba);
System.out.println(baba instanceof Object);
}
}


-> Upcasting

package org.example.lesson_13;

public class Main {
public static void main(String[] args) {
Ulubaba u = new Baba();
}
}


-> Downcasting

Problemsiz situasiya:

package org.example.lesson_13;

public class Main {
public static void main(String[] args) {
Ulubaba ulubaba = new Baba();
Baba baba = (Baba) ulubaba;
}
}


Problemli situasiya: ClassCastException

package org.example.lesson_13;

public class Main {
public static void main(String[] args) {
Ulubaba ulubaba = new Ulubaba();
Baba baba = (Baba) ulubaba;
}
}

Problemli situasiya2:

package org.example.lesson_14;

public class Athlete {
public String name;
public String surname;
}


package org.example.lesson_14;

public class Runner extends Athlete {
public boolean professionalRunningCertificate;

public void run() {
System.out.println("Runner runs 100 meter distance for 9 seconds");
}
}


package org.example.lesson_14;

public class Grappler extends Athlete {
public boolean professinalGrapplingCertificate;

public void grapple() {
System.out.println("Grappler grapple for 10 minutes non-sto");
}
}


package org.example.lesson_14;

public class Main {
public static void main(String[] args) {
Athlete athlete = new Grappler();
Runner runner = (Runner) athlete;
}
}


-> Polymorphism:

package org.example.lesson_14;

public class Main {
public static void main(String[] args) {
Athlete athlete = new Grappler(); // Polymorphism,
// athlete realda Grappler obyekti olmasina baxmayaraq
// ozunu Athlete obyekti kimi aparir
}
}



-> metod parametri super class teleb edir, lakin biz ora subclass gonderirik, ve metodun instanceof ishledilmesi

package org.example.lesson_13;

public class Ulubaba {
public String ad;
public String soyad;
public Integer yash;

public void odunDogramaq() {
System.out.println("Ulubaba 50 kq odunu 1 saata dograyir");
}
}
package org.example.lesson_13;

public class Baba extends Ulubaba {
public String hobbi;

public void otBicmek() {
System.out.println("Baba 1 hektar otu 1 gune bicir");
}
}
package org.example.lesson_13;

public class Ogul extends Baba {
public boolean bakalavrDerecesi;

public void ovEtmek() {
System.out.println("Ogul meshede 1 gune 10 dovshan ovlayir");
}
}
package org.example.lesson_13;

public class Main {
public static void main(String[] args) {
Ulubaba ulubaba = new Ulubaba();
Baba baba = new Baba();
Ogul ogul = new Ogul();
foo(ulubaba);
foo(baba);
foo(ogul);
}

public static void foo(Ulubaba object) {
if (object instanceof Ulubaba) {
object.odunDogramaq();
} else if (object instanceof Baba) {
Baba baba = (Baba) object;
baba.otBicmek();
} else if (object instanceof Ogul) {
Ogul ogul = (Ogul) object;
ogul.ovEtmek();
}
}
}

Burada foo metodunun daxilinde if shertlerinde cox diqqetli olmaq lazimdir. Hal hazirda cox boyuk problem var. Ashagidaki numunede bu problemi aradan qaldiracayiq.

Solution:

package org.example.lesson_13;

public class Main {
public static void main(String[] args) {
Ulubaba ulubaba = new Ulubaba();
Baba baba = new Baba();
Ogul ogul = new Ogul();
foo(ulubaba);
foo(baba);
foo(ogul);
}

public static void foo(Ulubaba object) {
if (object instanceof Ogul) {
Ogul ogul = (Ogul) object;
ogul.ovEtmek();
} else if (object instanceof Baba) {
Baba baba = (Baba) object;
baba.otBicmek();
} else if (object instanceof Ulubaba) {
object.odunDogramaq();
}
}
}


-> Ferz edekki bize bashqa mikroservisden bir obyekt gelir ve biz onu oz metodumuza gonderirik ve instanceof istifade etmekle hemin obyektin metodunu cagirmaq (haminin axtardigi numune)

package org.example.lesson_13;

import java.util.Random;

public class Main {
public static void main(String[] args) {
Object object = giveMeObject();
System.out.println(object.getClass().getName());
foo(object);
}

public static void foo(Object object) {
if (object instanceof Ogul) {
Ogul ogul = (Ogul) object;
ogul.ovEtmek();
} else if (object instanceof Baba) {
Baba baba = (Baba) object;
baba.otBicmek();
} else if (object instanceof Ulubaba) {
Ulubaba ulubaba = (Ulubaba) object;
ulubaba.odunDogramaq();
} else {
System.out.println("This is just simple Object");
}
}

public static Object giveMeObject() {
Object[] objects = {new Ulubaba(), new Baba(), new Ogul(), new Object()};
Random random = new Random();
return objects[random.nextInt(4)];
}
}



-> Metod parametri superclass massivi teleb edir ve biz ora muxtelif subclass-larin massivini gonderirik, ve hemin metodun icinde mueyyen bir superclass metodunu ishledirik

package org.example.lesson_13;

public class Ulubaba {
public String ad;
public String soyad;
public Integer yash;

public void odunDogramaq() {
System.out.println(this.getClass().getName() + " 50 kq odunu 1 saata dograyir");
}
}


package org.example.lesson_13;

import java.util.Random;

public class Main {
public static void main(String[] args) {
Ulubaba[] ulubabas = {new Ulubaba(), new Baba(), new Ogul()};
foo(ulubabas);
}

public static void foo(Ulubaba[] ulubabas) {
for (int i = 0; i < ulubabas.length; i++) {
Ulubaba ulubaba = ulubabas[i];
ulubaba.odunDogramaq();
}
}
}



->Employee, Manager, Director simple version:

package org.example4;

public class Employee {
public int no;
public String name;
public int year;
public String department;

public static final int BASE_SALARY = 500;

public Employee(int no, String name, int year, String department) {
this.no = no;
this.name = name;
this.year = year;
this.department = department;
}

public void work() {
System.out.println("Employee is working!");
}

public double calculateSalary() {
return year * BASE_SALARY;
}

public String printInfo() {
return "Employee{no=%d, name='%s', year=%d, department='%s'}".formatted(no, name, year, department);
}

public static int getBaseSalary() {
return BASE_SALARY;
}
}
package org.example4;

public class Manager extends Employee{
public String departmentManaged;

public static final int MANAGAMENT_PAYMENT = 5000;

public Manager(int no, String name, int year, String department, String departmentManaged) {
super(no, name, year, department);
this.departmentManaged = departmentManaged;
}
}
package org.simpleVersion;

public class Director extends Manager {
public double bonus;

public Director(int no, String name, int year, String department, String departmentManaged, double bonus) {
super(no, name, year, department, departmentManaged);
this.bonus = bonus;
}
}
package org.example4;

public class Main {
public static void main(String[] args) {
Employee e = new Employee(1, "Jack", 14, "Production");
System.out.println("Salary: " + e.calculateSalary());
e.work();
System.out.println(e.printInfo());
System.out.println("-------------------------------------------------------------");
Manager m = new Manager(2, "Andy", 3, "Production", "Production");
System.out.println("Salary: " + m.calculateSalary());
m.work();
System.out.println(m.printInfo());
System.out.println("-------------------------------------------------------------");
Director d = new Director(3, "Mike", 2,
"Management", "Management", 1000);
System.out.println("Salary: " + d.calculateSalary());
d.work();
System.out.println(d.printInfo());
}
}



-> Employee, Manager, Director example complicated version

package org.example4;

public class Employee {
public int no;
public String name;
public int year;
public String department;

public static final int BASE_SALARY = 500;

public Employee(int no, String name, int year, String department) {
this.no = no;
this.name = name;
this.year = year;
this.department = department;
}

public void work() {
System.out.println("Employee is working!");
}

public double calculateSalary() {
return year * BASE_SALARY;
}

public void printInfo() {
System.out.println("\nNo: " + no);
System.out.println("Name: " + name);
System.out.println("Year: " + year);
System.out.println("Department: " + department);
}

public static int getBaseSalary() {
return BASE_SALARY;
}
}
package org.example4;

public class Manager extends Employee {
public String departmentManaged;

public static final int MANAGEMENT_PAYMENT = 6000;

public Manager(int no, String name, int year, String department, String departmentManaged) {
super(no, name, year, department);
this.departmentManaged = departmentManaged;
}

@Override
public void work() {
System.out.println("Manager is working");
manage();
}

public void manage() {
System.out.println("Manager manages department: " + departmentManaged);
}

@Override
public double calculateSalary() {
return year * BASE_SALARY + MANAGEMENT_PAYMENT;
}

public void printInfo() {
super.printInfo();
System.out.println("Managing Department: " + departmentManaged);
}
}


package org.example4;

public class Director extends Manager {
public double bonus;

public Director(int no, String name, int year, String department, String departmentManaged, double bonus) {
super(no, name, year, department, departmentManaged);
this.bonus = bonus;
}

@Override
public void work() {
System.out.println("Director is working");
manage();
}

@Override
public void manage() {
System.out.println("Director manages whole company");
makeStrategicPlan();
}

public void makeStrategicPlan() {
System.out.println("Director makes a strategic plan for the company");
}

@Override
public double calculateSalary() {
return year * BASE_SALARY + MANAGEMENT_PAYMENT + bonus;
}

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


package org.example4;

public class Main {
public static void main(String[] args) {
Employee e = new Employee(1, "Jack", 8, "Production");
System.out.println("Salary: " + e.calculateSalary());
e.printInfo();
System.out.println("-------------------------------------------------------------");

Manager m = new Manager(2, "Andy", 3, "Production", "Production");
System.out.println("Salary: " + m.calculateSalary());
m.printInfo();
System.out.println("-------------------------------------------------------------");

Director d = new Director(3, "Mike", 20,
"Management", "Management", 1000);
System.out.println("Salary: " + d.calculateSalary());
d.printInfo();
}
}



-> Access modifiers. public -> protected -> default -> private

1) public - butun paketlerden ve butun siniflerden gorsenir

2) protected - eyni paketin icindeki butun klaslarda gorsenir, ve bawqa paketin icindeki klas eger hemin klasi extend edibse demeli gorsenecek

3) default - bu zaman variable veya metodun qarwisinda hecne yazilmir, buna package private-de deyilir

4) private - yalniz hemin klasin icinden gorsenir


->

package org.example.lesson13;

public class Parent {

public void foo() {
System.out.println("foo in Parent");
}
}
package org.example.lesson13;

public class Child extends Parent{

@Override
protected void foo() {
System.out.println("foo in Child");
}
}




-> Covariant return type


->

public class Shape { public void draw() { System.out.println("Drawing a generic shape"); } public Shape getShape() { return new Shape(); } } public class Circle extends Shape { @Override public void draw() { System.out.println("Drawing a circle"); } @Override public Circle getShape() { return new Circle(); } } public class Main { public static void main(String[] args) { Shape shape1 = new Circle(); Shape shape2 = shape1.getShape(); shape2.draw(); } }


->


package org.example4;

public class HR {
public Employee getAnEmployee() {
return new Employee(1, "Ali", 8, "Production");
}
}
package org.example4;

public class HRForManager extends HR{
public Manager getAnEmployee() {
return new Manager(2, "Vali", 3, "Production", "Production");
}
}
package org.example4;

public class HRTest {

public static void main(String[] args) {
HR hr = new HR();
Employee employee1 = hr.getAnEmployee();

HRForManager hrForManager = new HRForManager();
Employee employee2 = hrForManager.getAnEmployee();
employee2.work();

Manager manager = hrForManager.getAnEmployee();
manager.manage();
}
}


*** Ferz edek ki, bunun eksi baw verir. Hr klasinin getAnAmployee metodu Manger, HrForManager klasinin getAnEmployee metodu ise Employee return edir. Ve biz qiraqda bir metod yaradiriq, hansiki Hr qaytarir, metodun icinde ise HrForMangers obyektini qaytaririq(polymorphisme gore bu mumkundur). Ve bunu istifade eden insan gelir Hr klsina baxanda gorurki getAnEmployee Manger qaytarir, ve istifade eden insan emindirki Manager klasinin obyekti gelecek, lakin getAnEmployee-ni iwletdikde Employee-nin obyekti gelir. Yeni: Manager manager = new Employee(); olur bu ise xetadir.


-> Covariant return type-in pozulmasi. Sebeb ise Liskov substitution qaydasi pozulur(SOLID). Numune uzerinde gostermek

package org.lsp;

public class PayClassification {

public float calculateSalary() {
System.out.println("Salary for Monthly and Hourly");
return 0;
}

public void addTimeCardDetails() {
System.out.println("Timecard logic Monthly and Hourly salary");
}
}
package org.lsp;

public class MonthlySalary extends PayClassification {

public void monthlySalaryLogic() {
System.out.println("Monthly salary logic");
}
}
package org.lsp;

public class ComissionSalary extends PayClassification {

public float calculateSalary() {
System.out.println("Calculate salary for Comission");
return 0;
}

public void addTimeCardDetails() {
throw new RuntimeException("No Support");
}
}
package org.lsp;

public class Main {
public static void main(String[] args) {
PayClassification pay = new PayClassification();
pay.addTimeCardDetails();
pay.calculateSalary();
}
}

Liskov prinsipine gore biz super klasin obyektini istenilen sub klasa deyishe bilerik, ve kod qirilmamalidir. Lakin bizim halda bu qirilir:

package org.lsp;

public class Main {
public static void main(String[] args) {
PayClassification pay = new ComissionSalary();
pay.addTimeCardDetails();
pay.calculateSalary();
}
}






-> Overloading in subclass

package org.example4;

public class Parent {
public void foo(int i) {
System.out.println(i);
}
}
package org.example4;

public class Child extends Parent {

public void foo(String s) {
System.out.println(s);
}
}
Child child = new Child();
child.foo("Hi");
child.foo(1);


-> String klasinda equal() metodu, Object tipine String obyekti menimsetmek ve 
equals() metodunu yoxlamaq
String one = "Java";
String two = "Java";

System.out.println(one == two);
System.out.println(one.equals(two));

Object o1 = "Java";
Object o2 = "Java";
System.out.println(o1.equals(o2));






Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class