# Object Oriented Thinking — Part I

Prerequisites :

Terminology :

A bit of background about client!

Client is a fan of mathematics and they want to build an application that can compare two probabilities.

Implementation :

`import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        double p1 = scanner.nextDouble();        double p2 = scanner.nextDouble();        if (p1 == p2) {            System.out.println("P1 and P2 are equal");        } else {            System.out.println("P1 and P2 are not equal");        }    }}`
`java Main.java01P1 and P2 are not equal`

Retrospect :

Make it better ?

`//1. creating a class probabilitypublic class Probability {     //2. creating data member to hold probability value       private final double value;    //3. constructor to create probability object   public Probability(double value)         throws InvalidProbabilityException {        validate(value);        this.value = value;    }   //4. Equality check by accepting another probability      public boolean equals(Probability that) {        if (this == that) return true;        return this.value == that.value;    }    //5. validate probability range [0,...,1]    private void validate(double value)        throws InvalidProbabilityException {        if (value > 1 || value < 0) {            throw new InvalidProbabilityException();        }    }}`

Playing with above code

`//Create some objects using above classProbability probabilityOne = new Probability(1);Probability probabilityZero = new Probability(0);//Equate objectsprobabilityOne.equals(probabilityZero) => this will return false//Create some objects using above classProbability probabilityOne = new Probability(1);Probability anotherProbabilityOne = new Probability(1);//Equate objectsprobabilityOne.equals(anotherProbabilityOne) => this will return true`

--

--

Love podcasts or audiobooks? Learn on the go with our new app.