Java learned as so far:

Java variables,
Array, 2d array
Method
Different method invoking and return type
Class
– Class is actually a blueprint/specification/design
– A class can create as many as objects it needs to create
Object
– Earth is a software application where human and other thing is software objects.For creating object we need to create a human class
– Objects do particular behavior in a class
– Object exist only in application runtime actually when application is running
– Objects have identity,state and behavior

this keyword – it represent current object
Instance
Constructor – The costructor is a special method with the same name as the class and it’s used to instantiate objects from that class
– Every class has a by default constructor if we don’t put it manually
– The constructor is special method containing instructions for object creation. it can be said it is so called birth method. It has instructions for how the object will be born when the application starts up
Static keyword
Stack and heap memory
Garbage collection
Object oriented Programming = better organizing of code, it is a way to organize our code from multiple files by creating objects
Local variable
Reference variable
Instance variable
Inheritance
– Inheritance is the approach to get/transfer behaviour of one class to another
– We use extends keyword for inheriting, in inheritance we inherit from parent class which known as base class and the class which needs inheritation is known as child class or sub class/derived class
super keyword it extract constructor and it’s variable from parent class but reverse is not possible
Overrides
– Same method name with different purpose
– Same method name in parent class but in child class the method name is same but with different purpose
– Overrides means replace
– Override is not a good idea sometimes so we go for interface
Interfaces
– Interface is a contract with a class. The class needs to implements that method of the interface according to contract
– Interface has a method which does not need body, so it is just only to define, it is called as abstract method
– one parent class
– We use implements keyword while putting interface in a class
Abstract class
– When you don’t need all methods to invoke you can use abstract method, you can not make object from abstract class. Abstract method needs to be in abstract class. We use abstract keyword for both method and object to define abstract class and methods
– you can only extend abstract class but can not instantiate abstract class
– We can define abstract class as a type while creating object
Polymorphism

Loops
Exception Handling

Collection Framework
Wrapper class
Threading
Concurrency
Database

Jshell
Functional Interfaces
Lambda expressions

-Lambda helps us to use separate from associated object
– it can run without class
– We need to use lot of interfaces for this

Streams

Ei bold kora jayga diye project banaye banaye clear korte hobe
Italic kora jaygagula motamuti clear asey In Sha Allah, Alhamdulillah
The source is : Imtiaz Ahmed’s complete Java course

 

Master Object Oriented Design in Java course note

Association: It defines relationship between classes, it defines how the software will behave
Dependency Association: For example from code:

public class Driver {
    public void drive(Vehicle raceCar){
        raceCar.accelerate();
    }
}

A driver receives a vehicle reference only as driver then only he can drive or accelerate

Composition: A particular object . It imply ownership
for example in this code:

package Lesson_1;

public class Vehicle1 {
    Engine myEngine; //c
    public vehicle(Engine anEngine){
        myEngine=anEngine;
    }

    public void operateVehicle(){
        myEngine.start();
    }
}

Aggregation Association: It does not imply ownership

public class SchoolLanguageDepartment{

   SpanishCourse spanish;
   FrenchCourse french;
   HindiCourse hindi;
   BanglaCourse bangla;

}

Here Department to SpanishCourse relation is composite

But Course to Student relationship is not composite because it does not imply ownership a student can take many courses or not

public class HistoryCourse{

  Student[] registeredStudent;

}

We find this relationship from above diagram, the block diamond and white diamond is the part of UML diagram

Forming Association between objects:

public class NewsPaperCompany{

    Customer customer;

    public void setCustomer(Customer aCustomer){
        customer=aCustomer;
    }


}

has a relationship in customer .

Now when to stop delivery

public class Customer{

    NewsPaperCompany paperCompany;

    public void setNewsPaperCompany(NewsPaperCompany aPaperCompany)
    {
        paperCompany=aPaperCompany;
    }

    public void cancelSubscription{
        paperCompany.stopDelivery();
    }
}

Overview of software design:
For example: Hospital Employee Management System
Task of the software:
Hire and Terminate Employees
Print Reports(XML,CSV Formats)

Problem Statement:
Current status of the software

Tips for design:
– You must draw design in paper or whiteboard don’t go to code directly
– Don’t overdesign or overdraw
– We have to develop iteratively but early steps should be kept simple
– Class names should be nouns based on their intention

Single Responsibility Priniciple(SRP): Not all the things in the same class

Don’t repeat yourself(DRY):

Arrow sign always describe that it is depends on that dependency class:

 


DAO=Data Access Object

Single Responsibility Principle Special Notes:
A class should have only one single reason to change

 

Open closed principle sayings about class design:

Classes should be open for extension but closed for modification.

Open Closed Principle and Strategy pattern:
Software modules should be open for extension and closed for modification
In development lifecycle software requirements needs to be constantly pour in. If developed need to change the already made codes the design is fragile. Fragile means broken.

So open closed principle save engineers from fragile design

instanceof operator we used here in the code:
HotelManagementSystem class:

package OpenClosedPrinciple;

public class HospitalManagement {
    public void callUpon(Employee employee){
        if (employee instanceof Nurse){
            checkVitalSigns();
            drawBlood();
            cleanPatientArea();
        }else if (employee instanceof Doctor){
            prescribeMedicine();
            diagnosePatients();
        }
    }


    //Nurses
    private void checkVitalSigns(){
        System.out.println("Checking Vitals");
    }

    private void drawBlood(){
        System.out.println("drawing blood");
    }

    private void cleanPatientArea(){
        System.out.println("cleaning patient Area");
    }
    //Doctors
    public void prescribeMedicine(){
        System.out.println("Prescribed Medicine");
    }

    public void diagnosePatients(){
        System.out.println("Diagnose Patient");
    }

}

Here it is like a junk drawer

So we will make it changes because it is violating OCP principle. This chamging process is known as Strategy pattern. So let’s do it.

We could also do it with interface class except abstract class

Example after applying Strategy pattern:
Nurse.java

package OpenClosedPrinciple;

public class Nurse extends Employee {


    public Nurse(int id, String name, String department, boolean working) {
        super(id, name, department, working);
        System.out.println("Nurse in action: ");
    }


    private void checkVitalSigns(){
        System.out.println("Checking Vitals");
    }

    private void drawBlood(){
        System.out.println("drawing blood");
    }

    private void cleanPatientArea(){
        System.out.println("cleaning patient Area");
    }


    public void performDuties(){
        checkVitalSigns();
        drawBlood();
        cleanPatientArea();
    }
}

Doctor,java

package OpenClosedPrinciple;

public class Doctor extends Employee {
    public Doctor(int id, String name, String department, boolean working) {
        super(id, name, department, working);
        System.out.println("Doctor in action..");
    }


    public void prescribeMedicine(){
        System.out.println("Prescribed Medicine");
    }

    public void diagnosePatients(){
        System.out.println("Diagnose Patient");
    }

    public void performDuties(){
        prescribeMedicine();
        diagnosePatients();
    }

}

HospitalManagement.java

package OpenClosedPrinciple;

public class HospitalManagement {
    public void callUpon(Employee employee){
//        if (employee instanceof Nurse){
//            checkVitalSigns();
//            drawBlood();
//            cleanPatientArea();
//        }else if (employee instanceof Doctor){
//            prescribeMedicine();
//            diagnosePatients();
//        }
        employee.performDuties();
    }





}

 

Employee.java

package OpenClosedPrinciple;

abstract public class Employee {
    private int id;
    private String name;
    private String department;
    private boolean working;


    public Employee(int id, String name, String department, boolean working) {
        this.id = id;
        this.name = name;
        this.department = department;
        this.working = working;
    }

    public abstract void performDuties();

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", department='" + department + '\'' +
                ", working=" + working +
                '}';
    }
}

 

EmergencyRoomProcess.java

package OpenClosedPrinciple;

public class EmergencyRoomProcess {
    public static void main(String[] args) {
        HospitalManagement ERDirector=new HospitalManagement();
        Employee peggy=new Nurse(1, "Peggy","Emergency Department",true);
        ERDirector.callUpon(peggy);

        Employee suzan = new Doctor(2,"Suzan","Emergency",true);
        ERDirector.callUpon(suzan);

    }
}

To String Tutorial:

DemoToString.java

package SomeBasicThingsPractice;

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

        Student s1=new Student(11,"Robin");
//        System.out.println(s1.sname);
//        System.out.println(s1.rollno);
        System.out.println(s1.toString());
    }


}

class Student{
    int rollno;
    String sname;

    public Student(int rollno, String sname) {
        this.rollno = rollno;
        this.sname = sname;
    }


    public String toString(){
        return "Student name is: "+sname+" and roll no:"+rollno;
    }
}

Dependency Inversion Principle:
Device Manufacturing Company has:

The manufacturing process:
1. Assembly
2. Testing
3. Packaging
4. Storage

GeneralMAnufacturingProcess
UML diagram:

We depend on something in driving like car is stopping by traffic light
Imagine a life every car has different mechanism
Violation of Dependency Inversion Principle
When higher level modules depend on lower level ones succeptible to change
Dangers of coupling:
Tight coupling :

Well design software has single responsibility
This method says high level modules should not depend on lowlevel modules. It should depend on abstractions
Abstract classes and Interfaces don’t change as often as concrete classes/ derivatives
Cohesion means related things together.

This code I tried to run in class inside class but did not worked. Then I downloaded course code and run worked then again I tried to do with my directory structure then it worked.

Quizes from OOP course:
Q1:
Q2: The Dependency Inversion Principle states
Interfaces and abstract classes change far less often the concrete derivatives. Concrete classes should depend on Interfaces and abstract classes because they change less often and are higher level modules

Q3: In general the dependency inversion principle states that code should only depend on things that don’t change often
True
Liskov Substitution Principle:
Subtypes must be substitutable for their basetypes

There are some patterns which is not good known as Anti-pattern:
Here the link can be found


This is a ISA relationship, Nurse and Doctor depends on Employee class. Employee class is Abstract class

When it is adding a substitute teacher who does not work as like a teacher it violates the LISKOV pronciple as per this line of definition: Subtypes must be substitutable for their basetypes

So we changed to a new UML which does not violate LISKOV principle and did the code.

New UML:


Question 1:
The Liskov Substitution principle states, that child classes should not be substitutable in place of their parents.

Interface Segregation Principle:

Fat class is a class which has too many responsibilities.

CustomerTransaction

import java.util.Date;
import java.util.List;

public class CustomerTransaction implements Accounting, Reporting {

    private List<Product> products;
    private Customer customer;

    public CustomerTransaction(Customer customer,List<Product> products){
            this.products=products;
            this.customer=customer;
    }

    //methods for reporting
    @Override
    public String getName(){
        return "name";
    }

    @Override
    public Date getDate(){
        return new Date();
    }

    @Override
    public String getProductBreakDown(){
        String reportlist = null;
        for(Product product: products){
            reportlist+=product.getProductName();
        }
        return  reportlist;
    }

    @Override
    public void prepareInvoice(){
        System.out.println("invoice prepared....");
    }

    @Override
    public void chargeCustomer(){
    System.out.println("charged the customer");
    }


}
public class AccountsReceivable {

    private CustomerTransaction transactionObject;


    public AccountsReceivable(CustomerTransaction aTransaction){
        transactionObject=aTransaction;
    }

    public void postPayment(){
        transactionObject.chargeCustomer();
    }

    public void sendInvoice(){
        transactionObject.prepareInvoice();
    }




}
public class Product {

private int productID;

    public int getProductID() {
        return productID;
    }

    public void setProductID(int productID) {
        this.productID = productID;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    private String productName;

}
public class Customer {
    private String name;


    public String getName() {
        return name;
    }

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


    private Reporting transactionObject;

    public void generateReport(){
        System.out.println(transactionObject.getName()+" "+transactionObject.getProductBreakDown()+" "+transactionObject.getDate());
    }

}
import java.util.Date;

public interface Reporting {
    //methods for reporting
    String getName();

    Date getDate();

    String getProductBreakDown();
}
public interface Accounting {
    void prepareInvoice();

    void chargeCustomer();
}

From Quiz: Main Kotha about Interface Segregation Principle:

This principle does not have to do with the number of dependencies that may exist in an application. The principle simply states that modules should not have dependencies on code they do not use.

If a module does not use functionality from another module, there is no reason to have a direct dependency between them. There should be an abstraction in between to segregate the 2 modules

Dependency Injection: 
When the application is not running there is no object because onbject only available in runtime, you will find only some classes

Tight Coupling:
Cohesion:
A very popular dependency injection implementation is spring framework bundled with spring container.

Dependency injection is

Dependency Injection Using Spring:
Observer Pattern:
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

One basic UML diagram from wikipedia:

Created one for the course:

Builder Pattern:
When there is so many constructors and tough to handle it. Example codes with some bugs. Will do the solution later.

code example:
user.java

import java.lang.module.ModuleDescriptor;

public class User {
    private String userName; //Required
    private String emailAddress; //Required
    private String firstName; //Optional
    private String lastName; //Optional
    private int phoneNumber; //Optional
    private String address; //Optional

    public User(Builder builder) {
        this.userName=builder.userName;
        this.emailAddress=builder.emailAddress;
        this.firstName=builder.firstName;
        this.phoneNumber=builder.phoneNumber;
        this.address=builder.address;
    }

    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", emailAddress='" + emailAddress + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", phoneNumber=" + phoneNumber +
                ", address='" + address + '\'' +
                '}';
    }



    public static class Builder{
        private String userName; //Required
        private String emailAddress; //Required
        private String firstName; //Optional
        private String lastName; //Optional
        private int phoneNumber; //Optional
        private String address; //Optional

        public Builder(String userName,String email){
            this.userName=userName;
            this.emailAddress=email;
        }

        public Builder firstName(String value){
            this.firstName=value;
            return this;
        }

        public Builder lastName(String value){
            this.lastName=value;
            return this;
        }

        public User build(){
            return new User(this);
        }

    }

}

app.java

public class App {
    public static void main(String[] args) {
        User websiteUser = new User.Builder("bobMax", "bob@bob.com").firstName("bob").lastName("max").build();


        System.out.println(websiteUser);
    }
}

Factory Pattern:

UML Diagram:

codes:
Vehicle.java

public interface Vehicle {
   public void startEngine();
}

VehicleFactory.java

public class VehicleFactory {
    public Vehicle getVehicle(VehicleType vehicleType)
    {
        return vehicleType.getVehicle();
    }

}

App.java

public class App {
    public static void main(String[] args) {
        VehicleFactory vehicleFactory=new VehicleFactory();
        Vehicle vehicle=vehicleFactory.getVehicle(VehicleType.ELECTRIC);
        vehicle.startEngine();
    }
}

VehicleType.java

public enum VehicleType {
    TRUCK {
        public Vehicle getVehicle() {
            return new Truck();
        }
    }, CAR {
        public Vehicle getVehicle() {
            return new Car();
        }
    }, ELECTRIC {
        public Vehicle getVehicle() {
            return new ElectricCar();
        }


    };


    abstract Vehicle getVehicle();

    }

ElectricCar.java

public class ElectricCar implements Vehicle{

    @Override
    public void startEngine() {
        System.out.println("push button started electric car´s engine");
    }
}

Car.java

public class Car implements Vehicle{
    public void startEngine(){
        System.out.println("started simple engine");
    }
}

Truck.java

public class Truck implements Vehicle {

    @Override
    public void startEngine() {
        System.out.println("started a large engine");
    }
}

Singleton Design Pattern: It only uses once in an application.

PerformanceStage

public class PerformanceStage {
    //private constructor for singleton
    private static int counter;
    private static PerformanceStage INSTANCE=null;

    private PerformanceStage(){
        counter++;
    }
    public synchronized static PerformanceStage getInstance(){
        if(INSTANCE==null){
            INSTANCE = new PerformanceStage();
        }
        return INSTANCE;
    }

    public void turnOnLights(){
        System.out.println("turned on lights...");
    }

    public int getCounter(){
        return counter;
    }

}

Application.java

public class Application {
    public static void main(String[] args) {
        PerformanceStage stage=PerformanceStage.getInstance();
        stage.turnOnLights();
        System.out.println(stage.getCounter());


        PerformanceStage stage2=new PerformanceStage();
        PerformanceStage stage3=new PerformanceStage();
        PerformanceStage stage4=new PerformanceStage();
        PerformanceStage stage5=new PerformanceStage();

        System.out.println(stage3.getCounter());
    }
}

 

 

Course Source Imtiaz Ahmed Master OOP Design udemy course
Best Book Rereference/Website reference for learning Java: https://beginnersbook.com/2013/12/java-string-equals-and-equalsignorecase-methods-example/

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *