Monday, 10 May 2021

Classes and objects in java

 Classes and Objects are the very basic entity of object oriented programing. Without them, we can not proof any concept of object oriented programing.

That's why we need to give very high attention. First we need to understand what is the class?

Class in java

Class is a blueprint. For example we are going to build a home, first we need to prepare a blueprint on paper. Same as building home, class is a blueprint of objects.

Same as home have many attributes and behaviors, like

Attributes: Windows, doors etc.
Behaviors: Open window, Close window, Open door, Close door.

Object also have their attributes and behaviors. Attributes of object are the fields or instance variable, and behaviors of objects are methods.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.pervezblogger.example

import java.util.Date;

public class Bank{

	private String accountNumber;
	private String accountHolderName;
	private Date accountOpeningDate;
	private Double accountBalance;
	
	public Bank(String accountNumber, String accountHolderName){
	
		this.accountNumber = accountNumber;
		this.accountHolderName = accountHolderName;
		this.accountBalance = 0.0;
		this.accountOpeningDate = new Date();
	
	}

	public String getAccountNumber(){
	
		return accountNumber;
	
	}
	
	public String getAccountHolderName(){
	
		return accountHolderName;
	
	}
	
	public Double getAccountBalance(){
	
		return accountBalance;
	
	}
	
	public Date getAccountOpeningDate(){
	
		return accountOpeningDate;
	
	}
	
	public Double addBalance(Double amount){
	
		accountBalance+=amount;
	
		return accountBalance;
	}

}

Into provided example, we are taking Bank class. We have used so many keywords into this example, we will discuss them also latter.

Lets discuss the basic components of class.

For creating any class we need class keyword. Before class keyword, we can use public access specifiers. If class is public, then the name of .java file should be same as class name.
Each .java file should have at least one class with public access specifiers.

After the class keyword, we give the class name, here Bank is the class name. According to naming convention rules, class name should be meaning full, and should be Capitalized. It means, The first character should be capital, no use of spaces, and each word should be separate with Capital letter.

Now after the class name we will start the class block. In JAVA blocks are denoted with {}. The block defined the scope in JAVA.

Into the class block we defined the class members and constructors. In java there are mainly two class members.

  • Instance variables or attributes
  • Methods or behaviors
We will discuss about class members in detail letter.

Object in java

Object is the physical entity of class. For example, we have prepared blueprint of home, now we have started construction of our home. For construction home we need land, and for constructing object we need memory space. In java we have a special memory space for save object that is heap memory.

Classes have constructors which is helpful for creating objects. Constructor have same name as Class name, and no return type. It can also have parameters. If we don't create any constructor, then JVM assumes that there is a default constructor, which have no parameters, and have one statements, that is

super()

which is helpful to call super class constructor. As we know that, JAVA supports Inheritance, and if Class not extends any class then JVM assumes that class extends Object class. So basically Object is a Super class of all JAVA classes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package com.pervezblogger.example

public class Bank extends Object{

	public Bank(){
	
	   super();
	
	}

	//Class members

}


For creating object of any class we call constructor with new keyword.

It will returns the reference of object, which we can hold into the Compatible Reference variable, which is either Into self reference variable like, 

Bank bank = new Bank();

or into Super class Reference variable,

Object bankSuperClass = new Bank();

here Object is the super class of Bank class. Or into the implementing reference variable.

1
2
3
4
5
6
7
package com.pervezblogger.example

public interface BankInterface{

	//Abstract methods

}


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package com.pervezblogger.example

public class Bank extends Object implements BankInterface{

	public Bank(){
	
	   super();
	
	}

	//Class members

}


BankInterface bankInterface = new Bank();


Here we have a syntax for creating object and holding it into reference variable:

TypeOfReferenceVariable nameOfReferenceVariable = new Constructor(params);

as we can see into syntax, we can also call parametrized constructor for creating objects.

This keyword

This keyword is used to hold the reference of current object. 

What is current object? 😢 😕

the current object is where we are currently doing the operation. like as we can see into Bank class, we have used this keyword into constructor. Here this keyword is used to solve the ambiguity between the local variable and instance variable because both have same name. But the question is how this keyword solve the ambiguity?

Because here this keyword have reference of current object i.e. Bank object. And when we call 

this.accountNumber;

It means we have used the instance variable of current class object.

Important: This keyword cannot be use outside the class. It means if this keyword is used into any class, then this keyword refer to that class only.

If I use this keyword into Bank class, then it refers Bank class only.

Usage of this keyword

1. To solve the ambiguity between local variable and instance variable.
2. For calling the current class constructor. It is called constructor Chaining.
3. this key can also call method, but this feature have no use.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.pervezblogger.example

import java.util.Date;

public class Bank{

	private String accountNumber;
	private String accountHolderName;
	private Date accountOpeningDate;
	private Double accountBalance;
	
	public Bank(){
	
		this.accountBalance = 0.0;
		this.accountOpeningDate = new Date();
		
	}
	
	public Bank(String accountNumber, String accountHolderName){
		
		//Constructor chaining
		this();
		this.accountNumber = accountNumber;
		this.accountHolderName = accountHolderName;
		
	
	}

	public String getAccountNumber(){
	
		return accountNumber;
	
	}
	
	public String getAccountHolderName(){
	
		return accountHolderName;
	
	}
	
	public Double getAccountBalance(){
	
		return accountBalance;
	
	}
	
	public Date getAccountOpeningDate(){
	
		return accountOpeningDate;
	
	}
	
	public Double addBalance(Double amount){
	
		accountBalance+=amount;
	
		return accountBalance;
	}

}

Line number 22 shows constructor chaining.

Class members

Class have two types of class members

  • Instance variable
  • Methods
Static variables are also class members. We will discuss them on another blog.

The instance variable are belongs to the object. For example we are making the object of Bank class

Bank b1 = new Bank("312001000111", "John wick");
Bank b2 = new Bank("312001000112", "Alladin");

Then objects which are hold by b1 and b2 reference variable, have different values of instance variable.

Methods are used to create the operations into class. Into methods, we can also use Instance variables.

Wednesday, 5 May 2021

Polymorphism in java

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.

If we are taking a real time example, then a Person can be A Husband, A Son, An employee at time.

In JAVA there are mainly two types of polymorphism

  1. Compile time polymorphism
  2. Run time polymorphism

Compile time polymorphism


Compile time polymorphism also called as static polymorphism. This type of polymorphism achieved by method overloading.

Method overloading


Method overloading is a feature in which we can create more then one methods with the same name.

But the question is, why we need to make more then one methods with the same name?

For understanding this, we are taking an example of method from String class i.e. valueOf().

We can see that String.valueOf() method can take multiple type of arguments like Integer, Float, Double, Boolean, Long etc. We just need to pass the value into valueOf method, and it returns the String value.

Here we only need to know the name of one method for all type of arguments. That is the reason for method overloading, for making a single purpose methods or constructors with the different type or number of arguments.

Here I will provide you some points for method overloading

1. If methods have same name, have same number of arguments but different type of arguments, then it will be method overloading.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public void methodName(String arg){

}

public void methodName(Integer arg){

}

public void methodName(Float arg){

}

public void methodName(String arg){

}

public void methodName(Integer arg){

}


2. If methods have same name, have same number and types of arguments but different position, then it will be method overloading.


1
2
3
4
5
6
7
public void methodName(String arg1, Integer arg2){

}

public void methodName(Integer arg1, String arg2){

}


3. If methods have same name but different number of arguments, then it will be method overloading.



1
2
3
4
5
6
7
public void methodName(String arg1){

}

public void methodName(Integer arg1, String arg2){

}

4. If methods have same name and same signature like same number of arguments and same type, same position, but different return type, then it will be not method method overloading.


1
2
3
4
5
6
7
public Integer methodName(String arg1){

}

public String methodName(String arg1){

}

Basically return type of methods playing no role into method overloading. So please don't be confuse with return type.

Run time polymorphism

It is a process In which calling method is decided on runtime. It also known as Dynamic polymorphism.
It is achieved by method overriding.

Method overriding

In method overriding we define a method with the same name and same signature of Parent class.

It means, override method is a method, defined into child class, with the

  • Same name.
  • Same arguments (Same type and same order)
  • Same return type
of parent class.

Into method overriding, return type also should be same. If you will try to change the return type, it will be compile time error.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class ParentClass{

  public String methodName(String name){
  
	 return "Parent class says hello to "+name;  
  }

}

public class ChildClass extends ParentClass{


	@Override
	public String methodName(String name){
  
	 return "Child class says hello to "+name;  
        }

}

Tuesday, 4 May 2021

Abstraction in java

 As we know that, Abstraction is Hiding the complexity. Here we will learn that, to whom and what complexity we need to hide.

First thing which we need to know is what complexity we need to hide?

We need to hide the method implementations. Here we treat method implementations as a complexity. Why? we will see it soon.

To whom we need to hide? From the calling class, method or reference we need to hide those complexities.

Now for better understanding we will take a classic example that is ATM machine example which we studied so many times, when we read abstractions.

Let's suppose we are developing an application for ATM. As we know that in ATM we can do withdraw cash, check balance and change pin. So if any machine can do these three operations, can be an ATM machine.

As we know that in JAVA, operations are defined into methods. So if any class have these three methods, can be an ATM class.

Here we have made a contract for ATM class. Also we know that Interface is a contract for a class. So that we can make an Interface for ATM i.e.


1
2
3
4
5
6
7
public interface Atm{
	
	public boolean withdrawCash(Double amount);
	public Double checkBalance();
	public boolean changePin(Integer oldPin, Integer newPin);

}


Now as we can see that here we have three methods, 

1. withdrawCash

2. checkBalance

3. changePin

If any class Implements Atm interface, they have to override all these methods.

Ok, here we have achieved the abstraction. How?

Suppose we have have three ATMs, one is belongs to Bank of India, second is belongs to ICICI and third one belongs to PNB.

Now we will treat each bank as an Implementation class for ATM i.e.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class BankOfIndia implements Atm{

	public boolean withdrawCash(Double amount){
	
		// check the balance first then do withdraw oprations.
		return true;
	
	}
	public Double checkBalance(){
	
		//Check the balance
		
		return null;
	
	}
	public boolean changePin(Integer oldPin, Integer newPin){
	
		//Validate the old pin then change new pin
		
		return true;
	
	}
	

}




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Icici implements Atm{

	public boolean withdrawCash(Double amount){
	
		// check the balance first then do withdraw oprations.
		return true;
	
	}
	public Double checkBalance(){
	
		//Check the balance
		
		return null;
	
	}
	public boolean changePin(Integer oldPin, Integer newPin){
	
		//Validate the old pin then change new pin
		
		return true;
	
	}
	

}




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Pnb implements Atm{

	public boolean withdrawCash(Double amount){
	
		// check the balance first then do withdraw oprations.
		return true;
	
	}
	public Double checkBalance(){
	
		//Check the balance
		
		return null;
	
	}
	public boolean changePin(Integer oldPin, Integer newPin){
	
		//Validate the old pin then change new pin
		
		return true;
	
	}
	

}


Now these three classes have complexities which we need to hide. From Whom? 

From the calling class, or method or reference.

Now according to my statement, we can assume that, why we need Interface here? when we call any method from the calling class or method or reference, we don't need to know the method implementation, what we need to know is only it's definition.

But, abstraction is not only for hiding the method implementation, or if I use more easy word, code of method. The complexity is not only the method's code. But complexity is to choose which classe's object I have to choose.

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class Machine{

	private Atm choosedAtm;
	
	public Machine(Atm choosedAtm){
	
		this.choosedAtm = choosedAtm;
	}
	
	public Atm getAtm(){
	
		return choosedAtm;
		
	}

}

Suppose we have a Machine class, into machine class we have a constructor, which takes Atm interface as a parameter.

Now this Parameter don't know from which bank, the object is received. I mean to say, 

it can be one of them:


1
2
3
Machine m = new Machine(new BankOfIndia());
Machine m = new Machine(new Icici());
Machine m = new Machine(new Pnb());


So here Machine don't care from which class, reference of Atm is come, what he need to know is Atm have three methods which he need to operate.

Here we have hide the Complexity from the Machine class.


Inheritance in java

The meaning of Inheritance is "Comes from Parents".

Here we will learn how inheritance is helpful in JAVA.

Into Object oriented programing, Inheritance is a feature which is helpful to use the methods of parent class into the child class, or can call methods of parent class using the child class reference.

For example we have a class Car here:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Car{
 
   public void carHaveSeats(){
   
   }
   
   public void startEngine(){
   
   
   }

   public class shiftGear(){
   
   
   }

}

A car can be treat as a Super class.

Into this super class we have three methods:

1. carHaveSeats

2. startEngine

3. shiftGear

Now if we want to Make sub classes of cars it can be:

1. AutomaticCar

2. ManualCar



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class AutomaticCar extends Car{

	@Override
    public void shiftGear(){
	
		//Automatic shift
    }
	
     public void playMusic(){
	
     }

}



1
2
3
4
5
6
7
8
9
public class ManualCar extends Car{

	@Override
    public void shiftGear(){
	
		//Manual shift
     }
  
}


Here ManualCar and AutomaticCar class have one override method i.e shiftGear which is comes from Parent class i.e. Car


As we know that ManualCar and AutomaticCar is child class of Car, so they have 2 methods also which are derived from their Parent class i.e. Car.

1. carHaveSeats

2. startEngine


so with the help of Child class object, we can call these two derived methods also, and we don't need to override them. For example



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
ManualCar manualCar = new ManualCar();

manualCar.carHaveSeats();
manualCar.startEngine();
manualCar.shiftGear();

AutomaticCar automaticCar = new AutomaticCar();

automaticCar.carHaveSeats();
automaticCar.startEngine();
automaticCar.shiftGear();

Car car = new AutomaticCar();

car.carHaveSeats();
car.startEngine();
car.shiftGear();

As we can see from line number 1 to 11, we have created an object of Child class, call their methods. and we should not have confusion on that is if there is override method available, then that override method will be call otherwise derived method(Derived from Parent class) will be call.

Here shiftGear method is override method.

But into line number 13 we have a reference of car but object of AutomaticCar.

Can we do this? is there any error?

Yes, we can do this. It is the beauty of Inheritance and also it is the use of Abstraction into the Inheritance.

Here is the statement:

We can instantiate a reference variable of Parent class with the Child class object, but can not do vice versa.

So, The Car reference can call all it's method. and override methods will be call from the object, same as automaticCar reference.

But there is one difference between the car reference and automaticCar reference.

From automaticCar reference we can call 

automaticCar.playMusic()

method, because playMusic() method belongs to AutomaticCar only

but from the reference of Car, we can not call

car.playMusic()

because, playMusic method is not belongs to Car class.

The conclusion is, references know only there methods definition, they don't care about the object type.


Java supports below type of Inheritance:

1. Single Inheritance

2. Multilevel Inheritance

3. Hierarchical Inheritance


Single Inheritance:



Into Single Inheritance, One parent class have only one Child class.


Multilevel Inheritance:



Into multilevel Inheritance, Each child class have one Child class. But last child have not any child class.


Hierarchical Inheritance:




Into hierarchical Inheritance, one parent class have multiple Child classes.


We can see that above mentioned all type of Inheritance have one common things, i.e. No one can extends more then one class.

It is the base of Inheritance in JAVA. i.e. One class can extends only one class.


Use of super keyword:

A super keyword is use to hold the reference of super class. JAVA by default extends Object class, or we can say that Object class is a first super class in java.

So if we haven't extends any class, then by default extends Object class and super keyword holds Object class reference.

we can also call super class constructor from the child class constructor.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Car{
 
   private String name;
 
   public Car(){
	
   }
	
   public Car(String name){
      this.name = name;
   }
 
   public void carHaveSeats(){
   
   }
   
   public void startEngine(){
   
   
   }

   public class shiftGear(){
   
   
   }
   
   public String getName(){
   
		return name;
   }

}


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class AutomaticCar extends Car{

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

    @Override
    public void shiftGear(){
		
		//Automatic shift
	}
	
	public void playMusic(){
	
	}

}

we can also call super class methods using super keyword

for example if we want to call shiftGear method of Car class from the AutomaticCar class then we can call it using super keyword

super.shiftGear();


    Some documents mentioned that with the help of Interfaces, we can achieve multiple inheritance also

Oracle defines Multiple inheritance


Encapsulation In java

 Encapsulation means to bind things into one object. For example into capsule we put many medicines.

Encapsulations is also one of the very great feature of JAVA.

We bind all the data members of class into one Class is called Encapsulations.

But what is the need to encapsulate the data members?

The only reason is to make data initialization more accurate. For example


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class UserProfile{

   private String name;
   private int age;
   
   public void setName(String name){
   
     this.name = name;
   
   }
   
   public void setAge(int age){
   
      this.age = age;
   
   }

}

Here UserProfile class is the example of encapsulation. Into this class, we have made its data members private, so that other classes won't able to initialize them directly or can not get there values directly. Right now we haven't defined getters for data members, but defined setters.

Now, if we want to make a validation here,

  • name should not be null
  • age should be greater then 18
Those validation won't be work, if those data members are public, because one who initialize those data members, if he take care about the validation then only those data members initialize with the correct value, otherwise right now we can initialize name with null also and age can be less then 18, even though age can be negative also 😂

So lets make this encapsulate class more usable:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class UserProfile{

   private String name;
   private int age;
   
   private UserProfile(){
   
   }
   
   public UserProfile(String name, int age) throws Exception{
   
      setName(name);
	  setAge(age);
   
   }
   
   public void setName(String name) throws Exception{ 
   
    if(name==null){
	
	  throw new Exception("Name should not be null");
	
	}
    this.name = name;
   
   }
   
   public void setAge(int age) throws Exception{
   
      if(age<18){
	    
		throw new Exception("Age should not be less then 18");
	  
	  }
   
      this.age = age;
   
   }
   
   public String getName(){
   
      return name;
   
   }
   
   public int getAge(){
    
	 return age;
   
   }

}

Now, UserProfile class is strongly encapsulated. at-least we can say that 😉

Here we have made default constructer private, so that there should be no any default values into the data members.

For instantiate the object of UserProfile, we have made parameterized constructor. It is helpful to make sure that each data members have there value.

Now, we have made a small changes into setters of data members. Now they have conditions according to there validations, and if validation fails, they throw an Exception. 

Ooh wow, exception handling we have used here, also one of my favorite feature of JAVA. 

Well now it gives us surety that the data member will have their either correct value, or throw an exceptions, which will handle accordingly by the caller.

Sunday, 14 February 2021

Hibernate relationship one to one

 Types of relations:

1. One-To-One

2. One-To-Many

3. Many-To-One

4. Many-To-Many


1. One-To-One


one to one relationship can be of two types

a) Mandatory

b) Optional 


a) Mandatory


a.1) Using foreign key



Into above entity diagram as we can see that here we have two tables

1. Users

2. Address

If one user have only one address then we can use one to one relationship here.

For this we define address_id  column into users table.



import javax.persistence.*;

@Entity
@Table(name="users")
public class UserEntity {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;
	
	@Column(name = "user_name")
	private String userName;
	
	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name="address_id", referencedColumnName = "id")
	private AddressEntity addressEntity;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public AddressEntity getAddressEntity() {
		return addressEntity;
	}

	public void setAddressEntity(AddressEntity addressEntity) {
		this.addressEntity = addressEntity;
	}
	
	
	
}



import javax.persistence.*;

@Entity
@Table(name="address")
public class AddressEntity {

	private long id;
	
	@OneToOne(mappedBy="addressEntity")
	private UserEntity userEntity;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public UserEntity getUserEntity() {
		return userEntity;
	}

	public void setUserEntity(UserEntity userEntity) {
		this.userEntity = userEntity;
	}
	
	
}