Category Archives: oops

Java: HashCode and Equals Contract


In Java java.lang.Object is the superclass of all the classes provides two very important methods :

public boolean equals(Object obj)
public int hashCode()

See Also:

Internally these methods are used when need to check equality of objects but developer implementation prospects mainly used when need to implement HashMap because on that time developers have to implement these methods inside your User Defined class. Lot’s of the time when the developer is not aware of the contract of hashcode() and equals() method they make mistake and not received expected results from HashMap. Before going to detail of hashcode() and equals() contract, Let’s discuss first the problems.

Most Common Problem

In this example,  green and red car object is stored successfully in a HashMap, but when the map is asked to retrieve this green car object, the car object is not found in map and returning as null.

import java.util.HashMap;
import java.util.Map;

public class Car {
	private String color;

	public Car(String color) {
		this.color = color;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof Car))
			return false;
		if (obj == this)
			return true;
		return this.color.equals(((Car) obj).color);
	}
	public static void main(String[] args) {
		Car a1 = new Car("green");//hashcode
		Car a2 = new Car("red");

		// HashMap stores car type and its quantity
		Map m = new HashMap();
		m.put(a1, 10);
		m.put(a2, 20);
		//hashcode diffrent from previos green object consider different object
		System.out.println(m.get(new Car("green")));
	}
}
         

Output

null

The above program prints as null. However, we can check that this car object is stored in the map by inspecting in the debugger:

Java hashCode and Equals Contract

In the above program problem is hashcode() method was not implemented.

Before going to the solution to this problem in detail. We need to understand the equals() and hashcode() method contract.

hashcode() and equals() Method Contract

The contract between equals() and hasCode() is that:

  1.  If two objects are equal, then they must have the same hash code value.
  2.  If two objects have the same hashcode value, they may or may not be equal.

The main idea is Map worked on hashing techniques to find an object faster in comparison to linear search. In this case, because the hashcode() method is no implemented. It will call by default method of object class i.e return different hashcode value for different objects. In this above case both the objects store in HashMap and retrieving will have different hashcode values.

See Also: Java: Hashmap Working

In HashMap, store values in form array of buckets of the object where these array having hashcode value while objects having objects that match with the same hashcode. For example, the Hash Code is like a sequence of boxes for storage where different kinds of stuff can be stored in different boxes. It is more efficient if you organize stuff to a different place instead of the same garage. So it’s a good practice to keep kinds of stuff on related boxes i.e equally distribute the hashCode value.

The solution is to add hashCode() method to the Car class. Here we are getting hash value based on the size of color length as implemented below.

import java.util.HashMap;
import java.util.Map;

public class Car {
	private String color;

	public Car(String color) {
		this.color = color;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof Car))
			return false;
		if (obj == this)
			return true;
		return this.color.equals(((Car) obj).color);
	}

	public int hashCode(){
		return this.color.length();
}
	public static void main(String[] args) {
		Car a1 = new Car("green");//hashcode
		Car a2 = new Car("red");

		// HashMap stores car type and its quantity
		Map m = new HashMap();
		m.put(a1, 10);
		m.put(a2, 20);
		//hashcode different from previous green object consider different object
		System.out.println(m.get(new Car("green")));
	}

}

Output

10

Java: Aggregation and Composition (HAS-A)


Pre-requisite: Java: OOPS Concepts, Java: Class, Java: Object

If objects are having an association as “HAS-A” then there could be two types of relationship between objects:

  1. Aggregation
  2. Composition

Aggregation

Aggregation is a special type of association where objects have their independent life cycle but there is ownership. These owners and associate objects have the “HAS-A” relationship.

For Example, A person may associate with an Organization but he/she has an independent existence in the world.

Benefits of Aggregation

  • Aggregation provides reusability.

Note: For code reusability, if classes having IS-A relationship use Inheritance and for Has-A relationship use Aggregation.

Example of Aggregation

Here Employee class is associated with address class with Aggregation (HAS-A) relationship. Employee class contained an object of Address, this address object contains its own information like city, state, country, etc. Both of these objects are not strongly associate because if employee looses their jobs but still have the same address.

public class Address {
	String city, state, country;

	public Address(String city, String state, String country) {
		this.city = city;
		this.state = state;
		this.country = country;
	}

}

 

 

public class Employee {
	int id;
	String name;
	Address address;

	public Employee(int id, String name, Address address) {
		this.id = id;
		this.name = name;
		this.address = address;
	}

	void display() {
		System.out.println(id + " " + name);
		System.out.println(address.city + " " + address.state + " " + address.country);
	}

	public static void main(String[] args) {
		Address address1 = new Address("Noida", "UP", "India");
		Address address2 = new Address("Greater Noida", "UP", "India");

		Employee e = new Employee(101, "Saurabh", address1);
		Employee e2 = new Employee(102, "Gaurav", address2);

		e.display();
		e2.display();

	}
}

Composition

The composition is special type of aggregation where one object is strongly associated with another object and more restrictive. When the contained object in “HAS-A” and one object can not exist without the existence of others it’s the case of composition.

For Example:

  • Wheels in a car.
  • House has a room. Here the room can’t exist without the house.
  • An employee has a job. A job can’t exist without an employee.

Benefits of Composition

  • The composition provides reusability.
  • The composition can control the visibility of another object and reuse only when needed.

Examples of Compositions
Here Person and Job class having a composition relationship. In this case, Job class creates at runtime whenever a new person comes and we can change the salary from backend without change on client-side.

public class Person {
	//composition has-a relationship
    private Job job;

    public Person(){
        this.job=new Job();
        job.setSalary(1000L);
    }
    public long getSalary() {
        return job.getSalary();
    }
}
public class Job {
	private String role;
    private long salary;
    private int id;

    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public long getSalary() {
        return salary;
    }
    public void setSalary(long salary) {
        this.salary = salary;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

}
public class TestComposition {

	public static void main(String[] args) {
		Person person = new Person();
		long salary = person.getSalary();

	}

}

Examples of Compositions & Aggregation
Let’s have an example of a University, it’s department and professors associated with departments.

University & Department Association: It’s a composition association because without University will exist in any department.
Department and Professors Association: It’s aggregate association because both are associated but not having any dependency like if department close professor lose. Both are are an independent entities.

import java.util.List;

public class University {
	 private List departments;

     public void destroy(){
         //it's composition, when i destroy a university I also
		 //destroy the departments. they cant live without university instance
         if(departments!=null)
             for(Department d : departments) d.destroy();
         departments.clear();
         departments = null;
     }

}
public class Department {
	private List professors;
    private University university;

    Department(University univ){
        this.university = univ;
        //check here univ not null throw whatever depending on your needs
    }

    public void destroy(){
        //It's aggregation here, if we fire any professor then they
		//will come out of department but they can still keep living
        for(Professor p:professors)
            p.fire(this);
        professors.clear();
        professors = null;
    }

}
public class Professor {
	 private String name;
     private List attachedDepartments;

     public void destroy(){

     }

     public void fire(Department d){
         attachedDepartments.remove(d);
     }
}

Java: Inheritance (IS-A)


Pre-requisite: Java: OOPS Concepts, Java: Class, Java: Object

Inheritance is a process where child class acquired all the properties and behaviors of the parent class. Inheritance is used when one object is based on another object. Here parent class also called a superclass and child class called a subclass.

For Example,  Person is Parent class and Employee is a subclass of Person. which acquired all the properties and behavior of Person class.

Advantage of inheritance

What is code Reusability in Inheritance?

Inheritance facilitates to reuse the fields and methods of the parent class in child class syntax of Java Inheritance.

Syntax of Inheritance Declaration

class Subclass-name extends Superclass-name  
{  
   //fields 
   //methods   
}

In java, extends keyword is used to inherit a class where a new class derived properties and methods of an existing class. The class that inherited is called a Parent/Superclass, and a new derived class is called a child/subclass.

What You Can Do in a Subclass?

A subclass inherits all of the public and protected members(fields, methods and nested classes) of its parent class, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the private members of the parent class.

Constructors are not members of the class, so they are not inherited by child class, but the constructor of the parent class can be invoked from the child class by using super.

These inherited members can use as-is, replace them, hide them, or supplement them with new members:

  • Parent class inherited fields  can be used directly, just like any other class field.
  • You can declare a field in the child class with the same name as the one in the parent class, thus hiding it (not recommended).
  • You can declare new fields in the child class that are not in the parent class.
  • The inherited parent class methods can be used directly as they are.
  • You can write a methods in child class that has the same signature as the one in the parent class. i.e Method Overriding.
  • You can write a new static method in the child class with the same signature as on the parent class, thus hiding it.
  • You can declare new methods in the child class that are not in the parent class.
  • You can write a child class constructor that invokes the constructor of the parent class, either implicitly or by using the keyword super.

Example of Inheritance

In this example, Animal is a parent class which is extended by the Dog Child class. The animal class having properties name, breed, age and color. There is one method print() to print all these values. Dog subclass will inherit all these properties those having access modifiers as public and protected. Child class Dog print() method is calling parent class print() method by super keyword.

Java inheritance Example
Java Inheritance Example
//POJO Class
public class Animal {
	// private variables
	private String name;
	private String breed;
	private int age;
	private String color;

	// Getter and setter methods
	public Animal(String name, String breed, int age, String color) {
		this.name = name;
		this.breed = breed;
		this.age = age;
		this.color = color;
	}
    //Method of class
	public String print() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}
public class Dog extends Animal {
	private String type;

	public Dog(String name, String breed, int age, String color, String type) {
		// call super class constructor to initialize
		super(name, breed, age, color);
		this.type = type;
	}

	// Overriding method of parent class
	@Override
	public String print() {
		return "Dog [type=" + type + ", print()=" + super.print() + "]";
	}
}
public class TestInheritance {

	public static void main(String[] args) {

		 //Instance with Parameterize Constructor
	     Animal dog=new Animal("Tommy","Small Dog",5,"Black");
	     //calling super class method because reference to super class
	     System.out.println(dog.print());

	     Animal dog_tiny=new Dog("Tiny","Small Dog",4,"Black","Bichon Friese");
	     //calling super class method because reference to super class
	     System.out.println(dog_tiny.print());

	     Dog dog_big=new Dog("Tufan","Big Dog",4,"White","Spotted");
	     //calling sub class method because reference to sub class
	     System.out.println(dog_big.print());
	}
}

Output


Animal [name=Tommy, breed=Small Dog, age=5, color=Black]
Dog [type=Bichon Friese, print()=Animal [name=Tiny, breed=Small Dog, age=4, color=Black]]
Dog [type=Spotted, print()=Animal [name=Tufan, breed=Big Dog, age=4, color=White]]

Here from this output, you will see the print method called based on object not by references of the object.

Points about Inheritance

  • extends the keyword used to implement inheritance.
  • Java doesn’t support multiple inheritances. It’s possible by implementing multiple interfaces.
  • Inheritance has an “IS-A” relationship.
  • Excepting Object Class, which has no parent class, every class has one and only one direct parent class (single inheritance). In the absence of any other explicit parent class, every class is implicitly a child class of Object.

Type of Inheritance in Java

Java supports three types of inheritance only for classes:

  1. Single
  2. Multi-Level
  3. HierarchicalJava Types Of Inheritance

Note:

  • Multiple Inheritance is not supported in java through the class.
  • Multiple and Hybrid inheritance is supported in java through interface only.

Single Level Inheritance

As you have seen in the above example is a single level of inheritance.

Multi-Level Inheritance

class Animal{
void eat(){System.out.println("Animal eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("Dog barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("Baby Dog weeping...");}
}
class MultiLevelInheritanceTest{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output


Baby Dog Weepig...
Dog barking...
Animal eating...

Hierarchical Inheritance

class Animal{
void eat(){System.out.println("Animal eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("Dog barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("Cat meowing...");}
}
class TestHierchicalInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//Compile Time Error
}}

Output


Cat meowing...
Animal eating...

Why multiple inheritance is not supported in java?

Java doen’t support multiple inheritance for class because of fixing ambiguity of common members like fields or method.

Suppose, we have three claases ClassA, ClassB and ClassC where ClassC extends ClassA and ClassB which are having common method display(). If you call display() method from child class then not sure which method got called because of ambiguity.
Since java not support multiple inheritance that’s why throgh compile time exception.

class ClassA{
void display(){System.out.println("Inside Class A");}
}
class ClassB{
void display(){System.out.println("Inside Class B");}
}
//Compile time issue issue here
class ClassC extends ClassA,ClassB{
 //suppose if it were
 public static void main(String args[]){
   ClassC obj=new ClassC();
   //Here it will through compile time issue
   obj.display();
}

 

Java: Constructors


In Java, Constructors are used to creating and initializing the object’s state. The constructor also contains collections of statements to execute at time object creation.

Type of Constructors:

  • Default Constructor: A Constructor without any argument.
  • Parameterize Constructor: A Constructor with a number of arguments.

Points to Remember for Constructor

  • Constructor always has the same name as the class name in which it exists.
  • Constructor can not be used with keywords final, abstract, synchronized and static.
  • Constructors declaration with access modifiers can be used to control its access i.e so that restricts other classes to call the constructor.
  • All java classes must have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
  • If you declare any parameterize constructor then that is must write a default constructor.
  • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

Example of Constructors

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
	//Parameterize constructor
	//Constructor Overriding
	public Animal(String name, String breed)
    {
        this.name = name;
        this.breed = breed;
    } 

}

Object Creation By Constructor

Here you will see both ways to create objects of Animal Class by using the default and parameterize constructors.

public TestClass
{
	public static void main(String[] args)
	{
	 //Instance Default Constructor
	 Animal dog_tommy=new Animal();

	 //Instance with Parameterize Constructor
     Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
	}
}

Does the Constructor return any value?

A constructor doesn’t have return type while implementation, but the constructor returns the current instance of the class. We can write return statements inside the class.

Constructor Overloading

Similar to methods, we can overload constructors also by creating an object in many ways. Java compiler differentiates between these constructors based on signature (i.e numbers, type, and order of parameters).

What is Constructor Chaining?

Constructor chaining is the process of calling a constructor from another constructor for the current object.

Constructor chaining can be performed in two ways:

  • Within the same class: Use this() keyword for same class constructors.
  • From base class: Use super() keyword to call a base class constructor.

Rules of constructor chaining

  • The this() expression should always be the first line of statment in the constructor.
  • There should always be at least one constructor without this() keyword.
  • Constructor chaining can be performed in any order.

Constructor Chaining Example: Within Same Class

Use this() keyword for constructors in the same class. Here you will see the last constructor with two arguments calling the constructor with the keyword this() for four arguments.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
	//Parameterize constructor
	//Constructor Overriding
	public Animal(String name, String breed)
    {
	   //constructor chaining
	    this(name,breed,1,"black");
    }
}

Constructor Chaining Example: From Base Class

Use super() keyword to call a constructor from the base class. Here Constructor chaining occurs through inheritance. A sub-class constructor’s call the super class’s constructor first so that sub class’s object starts with the initialization of the data members of the superclass. There could be multilevel of classes in the inheritance chain. Every subclass constructor calls up the chain till class at the top is reached.


public class Person{
    private String name;
    protected String citizenship;

    public Person()
    {
    }

    public Person(String name, String citizenship) {
        super();
        this.name = name;
        this.citizenship = citizenship;
    }

    public void print() {
		System.out.println("Citizen:"+ citizenship + ",Name:" + name);
	}

}

 

public class Employee extends Person {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen) {
			}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		// super keyword use to call parent constructor
		//constructor chaining to parent class
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

}

What is the use of constructor chaining?

Constructor chaining is the mechanism to perform multiple tasks in a single constructor rather than creating a separate constructor for each task and make their chain. Constructor Chaining makes the program more readable.

Constructors Vs Methods

Constructor Method
Constructor(s) must have the same name as the class within which it defined. The method does not have the same name as the class in which defined.
Constructor(s) does not return any type. method(s) have the return type or void if does not return any value.
A constructor is called only once at the time of Object creation. Method(s) can be called any number of times.
In case constructor not present in class, the default constructor provided by the compiler. In the case of Method, the compiler doesn’t provide the default method.
Constructs invoked implicitly Methods invoked explicitly.

Java: Object


Pre-Requisite: Java:Class
In the previous post, you learn about the Java Class declaration, implementation, and types of classes. Here we will discuss Object which is the basic unit of Object-Oriented paradigm to represent real-life entities.

When an instance of a class is created is known as Object. These instances share attributes and behaviors i.e methods of the class. These values of attributes will be unique for each object i.e called state.

A java program may have lots of objects and these objects interact with each other by invoking methods. An object consists of :

  • Identity: It gives a unique name to the identification of an object and enables one object to interact with other objects.
  • State: It is represented by attributes/properties values of an object.
  • Behavior: It is represented by methods of an object to behave in a particular state.

Object Class

Let’s consider a class of Animal, which can have an object like Dog, Cow, Lion, Elephant, etc. Each of these animals has different properties like name, breed, age, and color.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

Example of an object: Dog

Declaration of Object

We declare a variable or object like (type variable_name;). This indicates to the compiler that this variable refers to data whose type is type. In the case of the primitive type, declaration allocates space for the variable as per type but in case of a reference variable, the type must be a concrete class name. Generally, In java, we don’t create an object of Abstract class and interface.

Syntax

access_modifier class_name object_name;

Example

Animal dog_tommy;

As declared above for variable dog_tommy, show this variable is of type Animal but this will not create any object instance i.e point to undetermined value (null) as long as an object not created.

Creation & Initializing an object

When we create an instance of an object by using the new operator. It will allocate memory for a new object and return a reference to that memory. This new operator also called the class constructor to initialize the attributes of the class.

Syntax

//default constructor
access_modifier class_name object_name=new class_name();
//parameterize constructor
access_modifier class_name object_name=new class_name(arg1,arg2..);

Example

//Default Constructor
Animal dog_tommy=new Animal();

//Parameterize Constructor
Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");

Note :

  • All classes have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
  • If you declare any parameterize constructor then that is must write a default constructor.
  • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

Complete Example

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

public TestClass
{
	public static void main(String[] args)
	{
	 //Instance Default Constructor
	 Animal dog_tommy=new Animal();

	 //Instance with Parameterize Constructor
     Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
	}
}

Output


Animal [name=Default, breed=null, age=0, color=null]
Animal [name=Tommy, breed=Small Dog, age=5, color=Black]

Ways to create an object of a class

This is the most common way to create an instance of an object by using new operators. Java also provides other ways to create instances of an object but internally uses a new keyword only.

  1. Object by new Operator
  2. Object by Class.forName().newInstance()
  3. Object by clone() method
  4. Object by Deserialization
  5. Object for Anonymous Class

Follow this link to know about each object creation ways in detail: Java: Object Creation Ways

 

Java: Type of Classes


Pre-Requisite: Java: Class
In a previous post, you have got an understanding of java class declaration and creation.

Types of classes

Java supports lots of types of classes:

  • Concrete Class
  • Abstract Class
  • POJO Class
  • Static Class
  • Nested Class/Inner Class
  • Final Class
  • Anonymous Class
  • Lambda Expression

Here we will discuss these classes in detail.

Concrete Class

A concrete class is a normal class that is not declared with Non-access modifiers as abstract, final, etc. This class can have an implementation of a parent, interfaces or own class methods.

Example: Concrete Class

//Example Concrete Class
public class CalculatorTest {
    static int add(int a , int b)
    {
    	return a+b;
    }
    static int substract(int a , int b)
    {
    	return a-b;
    }
    static int multiply(int a , int b)
    {
    	return a*b;
    }
    static int division(int a , int b)
    {
    	return a/b;
    }
	public static void main(String[] args) {
      System.out.println("4+5 ="+add(4,5));
      System.out.println("4-5 ="+substract(4,5));
      System.out.println("4*5 ="+multiply(4,5));
      System.out.println("4/5 ="+division(4,5));
	}
}

See Also: Java: Concrete Class Examples

Abstract Class

A class that is declared with the keyword abstract is known as an abstract class in Java. It can have abstract and concrete methods (method with the body). An abstract class can not be instantiated but need to extend to implement abstract methods.

Example: Abstract Class

args)
{
Vehicle v=new Car();
v.engine();
v=new Bike();
v.engine();
v=new Truck();
v.engine();
v=new Bus();
v.engine();
}
}

See Also: Java: Abstract Class Examples

POJO Class

A class with only private variables and public getter and setter methods is called as POJO(Plain Old Java Object) class. These getter and setter methods use private variables. This class is completely encapsulated.

Example: Pojo Class

//POJO Class
public class Animal {
	//private  variables
    private String name;
    private String breed;
    private int age;
    private String color;
    //Getter and setter methods
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getBreed() {
		return breed;
	}
	public void setBreed(String breed) {
		this.breed = breed;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
}

See Also: Java: Pojo Class Examples

Static Class

A static class is a nested class declared as a static member of the class.

Example: Static Class

import java.util.Scanner;

public class StaticClasses {
	static int s;// static variable

	// static method
	static void printSum(int a, int b) {
		s = a + b;
		System.out.println(a + "+" + b + "=" + s);
	}

	static class NestedStaticClass//static class
	{
		static//static block
		{
			System.out.println("Inside Nested Class Static Block");
		}

		public void display()
		{
			Scanner scanner=new Scanner(System.in);
			System.out.println("Enter value of a:");
			int a= scanner.nextInt();
			System.out.println("Enter value of b:");
			int b= scanner.nextInt();

			printSum(a,b);
			System.out.println("Sum of numbers a+b:" +s);

		}
	}
}

public class StaticClassTest {

	public static void main(String[] args) {
		StaticClasses.NestedStaticClass nss=new StaticClasses.NestedStaticClass();
		//call method of nested class method
		nss.display();
	}
}

See Also: Java: Static Keyword & Examples

Nested Class/Inner Class

A Class declared inside of another class is called Nested Class/Inner Class.

Example: Nested Class/Inner Class

public class OuterClass {

	//nested/Inner Class: Class inside the class
	class NestedClass
	{
		public void innerMethod()
		{
			System.out.println("Inner Class Print");
		}
	}

	public static void main(String[] args) {
		System.out.println("Outer Class Print");

	}

}

See Also: Java: Nested/Inner Class Examples

Final Class

A Class declared with the final keyword is known as Final Class. This class can not be extended by another class. For Example java.lang.System, java.lang.String

Example: Final Class

public final class FinalClass {
 public void display()
 {
	 System.out.println("Display final class method.");
 }
}

//show compiler error :
//"The type BaseClass can not subclass the final class FinalClass"
class BaseClass extends FinalClass{
	public void display()
	 {
		 System.out.println("Display base class method.");
	 }
}

See Also: Java: Final Keyword & Examples

Anonymous Inner Class

Anonymous Class is an inner class without a name and for which only a single object is created. Such class is useful when you need to create an instance of an object such as overloading methods of a class or interface, without having to actually subclass a class.

Anonymous inner classes are mostly used in writing implementation classes for listener interfaces in graphics programming.

Example: Anonymous Class

//Using Anonymous Inner class Thread that extends a Class
class MyThread
{
    public static void main(String[] args)
    {
        //Here we are using Anonymous Inner class
        //that extends a class i.e. Here a Thread class
        Thread t = new Thread()
        {
            public void run()
            {
                System.out.println("Child Thread");
            }
        };
        t.start();
        System.out.println("Main Thread");
    }
}

See Also: Java: Anonymous Class Examples

Lambda Expression

Lambda expressions added in Java 8. It useful to create instances of functional interfaces (An interface with single abstract method). For Example: java.lang.Runnable is having one abstract method as run().

Example: Lambda Expression

public class LamdaTest {
	public static void main(String[] args) {
		new Thread(() -> System.out.println("This is Lamda test")).start();
	}
}

See Also: Java: Lamda Expression Examples

 

Java: Class


A Class is a blueprint or prototype from which objects are created. A class has properties and behaviors i.e methods that are common to all objects of the same type.

Object Class

Syntax of Class Declaration


Access_Modfier Non_access_modiers class class_name 
    extends super_class 
    implements interface1, interface 2..
{
fields
......
default constructor
......
parametrize constructor
......
methods
......
}
  • Access Modifiers: A modifier defined access scope of class, fields, and methods. If specifically not mentioned consider as default. See Also: Java: Access Modifiers/Specifiers
  • Class name: The class name should begin with an initial capital letter follow camel notation. See Also: Java: Identifier Naming Conventions
  • Non-Access Modifiers (if any): non-access modifiers can also be used on the class level to make a class special. See Also: Java: Non-Access Modifiers
  • Superclass(if any): A class can extend only one class i.e called parent class or superclass.
  • Interfaces(if any): A class can implement one or more interfaces. Their interfaces proceed by keyword implements and separated by a comma.
  • Body: A class body is surrounded by curly braces, { }.
    Fields: A class fields are variables that provide the state of class and it’s objects.
  • Methods: class methods are defined to implement the behavior of class and objects. See Also: Java Methods
  • Constructors: Java class constructors are used to initialize new objects. See Also: Java: Constructors

Note:

  • If a class is declared with access modifier public then java file name would also be the same. One Java file can have only one public class.
  • All the class extends Object Class i.e Object class is the superclass of all the classes.See Also: Java: java.lang.Object Class & Methods

Java Class Example

This is a very simple example of a class name as Animal. It’s having variables, constructors, methods and overriding method of superclass Object.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    } 

    //Instance methods
    public String getName()
    {
        return name;
    } 

    public String getBreed()
    {
        return breed;
    } 

    public int getAge()
    {
        return age;
    } 

    public String getColor()
    {
        return color;
    }
    //methods override from Object class
	@Override
	public String toString() {
		return "Animal [name=" + name + ", breed=" + breed + ", age=" + age + ", color=" + color + "]";
	}
}

Now we have got a basic understanding of class declaration and implementation. In the further post, you will learn about the types of classes and uses.

Types of classes

Java supports lots of types of classes:

  • Concrete Class
  • Abstract Class
  • POJO Class
  • Static Class
  • Nested Class/Inner Class
  • Final Class
  • Anonymous Class
  • Lambda Expression

Follow this link to know about all these classes and uses.

See Also: Java: Type of classes

Java: Abstract Class Vs Interface


Abstract class and interface in java used to provide abstraction but there are lots of differences:

Abstract Class Interface
Abstraction(0 to 100%) Abstraction(100%)
Abstract class implemented by keyword ‘extends Interface implemented by using keyword ‘implements
Abstract class also can not be instantiated but can be invoked if the main() method exists. Interface is completely abstract i.e can not create an instance of it.
Abstract class can have abstract and non-abstract methods. Interface methods are implicitly abstract and can not have an implementation(nobody)
Abstract class allowed final,non-final and static variables also. Interface allowed only final and static variables
Abstract class members are private, protected, etc. Interface members are public by default.
Abstract class can extend only one class but implements multiple java interfaces. Interface can extend other interfaces only.
Abstract class is fast compare to interface Interface is slow because it required extra indirection.
See Also: Java Abstract Class Examples See Also: Java Interface Examples

See Also:

Java: Interface


An interface is the blueprint of a class to achieve total abstraction.

  • Abstract Class: Abstraction (0 to 100%)
  • Interface: Abstraction (100%)

Points to remember for Interface in Java

  • Interface in java use interface keyword to declare.
  • Interface in java allows only abstract methods i.e methods don’t have a body.
  • Interface in java allows static constants.
  • Interface in java supports multiple inheritance.
  • Interface in java not required to declare the method as public and abstract, internally all methods are public and abstract.
  • Interface in java having all fields as public, static and final.
  • Interface in java represents the IS-A relationship.
  • Interface in java can not be instantiated just like an abstract class.

Note:
There are some enhancements in the interface as per Java versions:

  • Java 8 introduced default and static methods in an interface.
  • Java 9, allowed to support private methods in an interface.

Why use Java interface?

There is the main reason to use interface in java:

  • Interface in java used to achieve abstraction.
  • Interface in java is used to support the multiple inheritance functionality.
  • Interface in java is used to achieve loose coupling.

How to declare an interface?

Interface in java is declared by using the interface keyword. All interface methods declared with the empty body are by default public and abstract. All declared fields inside the interface are public, static and final by default.

If a java class that implements an interface must implement all the methods declared in the interface.

Syntax:

interface interface_name{  
     // declare constant fields by default public , static and final  
    // declare methods that public and abstract by default   
} 

Note: If you are not adding any modifier in methods and variables in Java interface. The compiler adds as below while compilation:

  • Java compiler will add the public and abstract before the interface methods.
  • Java compiler will add public, static and final before fields inside java interface.

Java Classes and Interface Relationship

In java a class extends another class, an interface extends another interface, but a class implements an interface.

Interface Example

In the given example, the Shape interface has only one method as draw(). This method is implemented by Rectangle and Circle classes.

In a real scenario, an interface provides an abstraction to users i.e interface is defined by someone else, but its method implementation is provided by different providers. Moreover, it is used by someone else to interact with the method but the implementation part is hidden by the user.


interface Shape{
	void draw();
}
class Rectangle implements Shape{
public void draw(){System.out.println("Drawing Rectangle Shape");}
}
class Circle implements Shape{
public void draw(){System.out.println("Drawing Circle Shape");}
}  

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

Shape d=new Circle();
      d.draw();
	  d=new Rectabgle();
      d.draw();
}}

Output


Drawing Circle Shape
Drawing Rectangle Shape

Multiple inheritances in Java by the interface

Multiple inheritance in java class can be achieve by implements multiple interfaces, or an interface by extends multiple interfaces.

interface Printable{
void print();
}
interface Shape{
void draw();
}
class Rectangle implements Shape,Printable{
public void draw(){System.out.println("Drawing Rectangle Shape");}
public void print(){System.out.println("Print Rectangle Area");}
}
class Circle implements Shape,Printable{
public void draw(){System.out.println("Drawing Circle Shape");}
public void print(){System.out.println("Print Circle Area");}
}
class TestMultipleInterface{
public static void main(String args[]){
Shape d=new Circle();
d.draw();
d.print();
d=new Rectabgle();
d.draw();
d.print();
}
}

Output


Drawing Circle Shape
Print Circle Area
Drawing Rectangle Shape
Print Rectangle Area

Multiple inheritances are not supported through the class in java, but it is possible by an interface, why?

Multiple inheritances are not supported in the case of class because of ambiguity but supported by the interface because there is no ambiguity. It is because this method implementation is provided by the implementation class.

As shown in the below example,  Showable and Printable interface have the same display() methods but its implementation is provided by class MultipleInterfaceExmple, so there is no ambiguity.

interface Printable{
void display();
}
interface Showable{
void display();
}

class MultipleInterfaceExmple implements Printable, Showable{
public void dispaly(){
System.out.println("Print Test Multiple Inheritance in java");
}
public static void main(String args[]){
MultipleInterfaceExmple obj = new MultipleInterfaceExmple();
obj.print();
}
}

Output

Print Test Multiple Inheritance in java 

Interface inheritance

A class implements an interface, but one interface can extend another interface.

interface Printable{
void display();
}
interface Showable extends Printable{
void show();
}
class InterfaceInheritanceExmple implements Showable{
public void print(){System.out.println("Print Interface Inheritance in java");}
public void display(){System.out.println("Display Interface Inheritance in java");}

public static void main(String args[]){
InterfaceInheritanceExmple obj = new InterfaceInheritanceExmple();
obj.print();
obj.display();
}
}

Output

Print Interface Inheritance in java
Display Interface Inheritance in java

What is a marker or tagged interface?

An interface that has no methods is known as a marker or tagged interface, for example, Cloneable, Serializable, Remote, etc. Marker Interface in Java is used to provide information to the JVM so that JVM treats these objects specially.

Follow below link to get Detail knowledge of Marker interface with examples:

Marker Interface in Java and Uses

What is nested Interface?

An interface declared within another interface or class is called a nested interface.

Follow below link to get detail knowledge of nested interface with examples:

Java: Nested Interface

 

Java: Nested Interface


An interface declared within another interface or class is called a nested interface.

The nested interfaces in java are used to group related interfaces so that easily maintain. The nested interface can’t be accessed directly. For accessing must be referred to by the outer interface or class.

For example, the Nested interface is just like almirah inside the room, for accessing almirah, first need to enter the room.

In the java collection framework,  Entry is the subinterface of Map i.e. accessed by Map. Entry.

Points to remember for nested interfaces

  • Nested interfaces are declared static implicitly.
  • Nested interface can have any access modifier while inside the class but if use inside interface then it must be public.

Syntax of Nested Interface inside Class

class class_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}

Syntax of Nested Interface inside Interface

interface interface_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}  

Example of Nested Interface: Interface within Interface

interface Readable{
  void show();
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Interface

we are accessing the Message interface by its outer interface Readable because it cannot be accessed directly.

class NestedInterfaceExample1 implements Readable.Message{

 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
  //upcasting here
  Readable.Message message=new NestedInterfaceExample1();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Note: For the above example when you compile Readable class, compiler internally creates the public and static interface as given below:

public static interface Showable$Message
{
  public abstract void messageDetail();
}

As you can see in the above example, The java compiler internally creates the public and static interface.

Example of Nested Interface: Interface within Class

In the below example you will see, interface implementation inside the class and how can we access it.

class ClassA{
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Class

class NestedInterfaceExample2 implements ClassA.Message{
 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
 //upcasting here
  ClassA.Message message=new NestedInterfaceExample2();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Can we define a class inside the interface?

Yes, If we implement a class inside the interface, the java compiler automatically creates a static nested class. In this example you will see how can we define a class within the interface:

interface M{
class A{}
}

 

Java: Abstract Class


Abstraction in Java

Abstraction is a concept to show only essential detail i.e hide internal detail and show functionality in simple terms. To achieve abstraction in Java, use abstract class or interface.

Example: In ATM we don’t know how internally work. In a Car don’t know about the internal mechanism.

Ways to achieve Abstraction

We can achieve abstraction in two ways:

  1. Abstract class: abstraction (0 to 100%)\
  2. Interface: abstraction (100%)

Abstract class in Java

A class that is declared with the keyword abstract is known as an abstract class in Java. It can have abstract and concrete methods (method with the body). An abstract class can not be instantiated but need to extend to implement abstract methods.

abstract class ClassA{}  

Points to Remember

  • Abstract class must be declared with the keyword abstract.
  • Abstract class can have abstract and non-abstract methods.
  • Abstract class cannot be instantiated.
  • Abstract class can have constructors and static methods also.
  • Abstract class can have final methods that will force the subclass not to change the body of the method.
  • Abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and even main() method.

Abstract Method in Java

A class method that is declared with keyword abstract and not having any implementation is known as an abstract method.

For Example

abstract class ClassA{
//no method body and abstract
abstract void printStatus(); 
}  

Note:

  • Rule 1: If a class having one or more abstract method then make to class as an abstract class by declaring with keyword abstract.
  • Rule 2: If a class is extending with an abstract class that has an abstract method, then the subclass must either need to make an abstract class or provide the implementation of the method.
  • Rule 3: The abstract class can also be used to provide some implementation of the interface. In this case, the programmer may not be forced to override all the methods of the interface.

Example of an abstract method

Let’s have a real scenario, Consider a group of vehicles like Bike, Bus, Car and Truck, and each vehicle has similarities like fuel amount, capacity, brakes, etc.

For this example, define Vehicle class as abstract with this method declaration as engine() because are similarities with all vehicles. Every vehicle has different ways to implement it so write an implementation of these methods in respective classes.

abstract class Vehicle{
  abstract void engine();
}

class Car extends Vehicle{
void engine(){
System.out.println("Car Engine is running safely");
} 

class Bike extends Vehicle{
void engine(){
System.out.println("Bike Engine is running safely");
} 

class Truck extends Vehicle{
void engine(){
System.out.println("Truck Engine is running safely");
} 

class Bus extends Vehicle{
void engine(){
System.out.println("Bus Engine is running safely");
}
} 

public TestAbstractClass
{
  public static void main(String[]args)
  {
    Vehicle v=new Car();
	v.engine();
	v=new Bike();
	v.engine();
	v=new Truck();
	v.engine();
	v=new Bus();
	v.engine();
  }
}

Output

Car Engine is running safely
Bike Engine is running safely
Truck Engine is running safely
Bus Engine is running safely

Mostly, we don’t know about the implementation class (which is hidden to the end-user), and an object of the implementation class is provided by the factory method.

abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 9;}
}    

class TestBankDetail{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("ICICI Rate of Interest is: "+b.getRateOfInterest()+" %");
}}

Output

SBI Rate of Interest is: 8 %
ICICI Rate of Interest is: 9 %

Java: OOPS Concepts


The object is Real-world entities i.e Pen, Paper, computer, watch, fan, etc.

Object-Oriented Programming is a paradigm or methodology to implement real-world entities by design a program using classes and objects.

OOPS(Object-Oriented programming System) provides a paradigm to simplifies the development and maintenance of a Software. Here are the main concepts of OOPS:

  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

Apart from these basic concepts, there are some other terminologies used to show association and dependency between the objects: and classes:

  • Coupling
  • Cohesion
  • Association
  • Aggregation
  • Composition
  • Generalization(Super Class)
  • Specialization (Sub Class)
  • Realization(Interface)

See Also:

  • Java: Class & Instance Relationship
  • Java: OOPS Design Principles
  • Java: SOLID Design principles

simula and Smalltalk are considered as first truly object-oriented programming language But the main popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

OOPS Concept

Object

A physical or logical entity that has state and behavior are known as an object. For Example Pen, Paper, computer, watch fan, etc.

An Object is an instance of a class. It contains an address and takes some space in heap memory. Communication between objects happens without knowing the detail of each other only condition is the type of message accepted and the type of response returned should be compatible.

For Example, A car is an object because it has states like color, make, model, engine, etc. as well as behaviors like speed, accelerator, music, etc.

Class

The collection of objects is called a class. Class is the blueprint of an object from which object created. Class doesn’t consume space.

For Example, Person is class and “Saurabh Gupta” is the object of that class.

Inheritance

Inheritance is a process where child class acquired all the properties and behaviors of the parent class. Inheritance is used when one object is based on another object. Here parent class also called a superclass and child class called as a subclass.

For Example,  Person is Parent class and Employee is a subclass of Person. which acquired all the properties and behavior of Person class.

Advantage of inheritance

  • Code Reusability
  • Runtime Polymorphism

Points about Inheritance

  • extends the keyword used to implement inheritance.
  • Java doesn’t support multiple inheritances. It’s possible by implementing multiple interfaces.
  • Inheritance has an “IS-A” relationship.

Polymorphism

Polymorphism (more-form) means the ability to take more than one form. It’s used when one task needs to perform in different ways.

For Example, areas of shape are having different formulae for each same like rectangle, square, circle, etc.

Polymorphism can be achieved in two ways:

  1. Runtime Polymorphism (Method Overriding)
  2. Compile-time Polymorphism (Method Overloading)

Abstraction

Abstraction is a concept to show only essential detail i.e hide internal detail and show functionality in simple terms. To achieve abstraction in Java, use abstract class or interface.

Example: In ATM we don’t know how internally work. In Car don’t know about the internal mechanism.

Abstraction can be achieved by two ways:

  • Abstract Class (0% to 100%)
  • Interface (100%)

Encapsulation

Binding (or wrapping) of data and function in a single unit is called encapsulation. The encapsulation technique is used to achieve abstraction in oops.

In Java, A class is an example of encapsulation where abstraction level depends on access modifiers(private, protected and public) uses for fields and methods. A class is considered as fully encapsulated if all data members are private.

 

Java: package and import Keyword


Java package is a mechanism to a group of similar types of classes, interfaces, and sub-packages. java Package categorizes in two forms:

  1. Built-in Package
  2. User Define Package

Built-in Package

Java provides lots of built-in packages as per specific requirements. Here is a list of most frequently used built-in packages:

Package Name Description
java.applet It provides the classes related to applet creation and communicates with its applet context.
java.awt It contains the classes for creating user interfaces designing graphics and images.
java.beans It provides classes related to developing components based on the JavaBeans architecture.
java.io Provides classes and interfaces for input and output through data streams, serialization, and the file system.
java.lang It provides fundamental classes to the design of the Java programming language.
java.math It provides classes for performing mathematical operations for integer arithmetic (BigInteger) and decimal arithmetic (BigDecimal).
java.net Provides the classes related to implementing networking applications.
java.nio Defines buffers classes which are containers for data.
java.rmi Provides the classes related to RMI.
java.security Provides the interfaces and classes for the security framework.
java.sql Provides the API for processing and accessing data stored in a data source.
java.time The Classes and Methods to deal with dates, times, instants, and durations.
java.util Provide Collections framework classes and interfaces, date and time facilities, internationalization, and miscellaneous utility classes like (string tokenizer, random-number generator, and bit array).

You can get refer the complete list of Java packages from this link : Java: Complete Package List

java Most Common Built in packages

Here we will mainly focus on User Defined Packages creation and access.

Advantage of Java Package

  1. Java package is used to group the classes and interfaces so that they can be easily maintained.
  2. Java package removes naming conflicts.
  3. Java package provides access protection.

Rule of Java Package

There are certain rules that need to follow while creating the java class files.

  • Rule 1: Declare package as the first line of the statement in class or interface or a .java file. Which shows the directory location of java file after compilation.
  • Rule 2: A single java source file can have only one public class and this file will save with public class name only.
  • Rule 3: Two same name source files can not be in the same package.
  • Rule 4: If a source file is not having a package name i.e consider in the default package.
  • Rule 5: A class accessing another class, if both are in the same package then don’t require a package name.

Java Package Example

package mypackage;
public class SimplePackageExample{
public static void main(String args[]){
System.out.println("Welcome to My Package");
}
}

How Java Package Compilation?

If you are not using any IDE, you need to follow the syntax in command-line as given below:

javac -d directory java_file_name  

For example:

javac -d . SimplePackageExample.java  

The -d argument represents destination i.e use switch specifies the destination where to put the generated class file.

Note: Use dot(.) to keep package within the same directory/current folder. You can put directory path in place of the dot(.) to move compiled class file on that location. For Example Use /home (in case of Linux), d:/myclasses (in case of windows), etc.

Java Package Program Execution

You need to use a fully qualified name e.g. mypackage.SimplePackageExample etc to run the class.

To Compile: javac -d . SimplePackageExample.java
To Run: java mypackage.SimplePackageExample
Output:Welcome to My Package

How to access package classes from another package?

Java provides three ways to access the package from outside the package:

  1. import package.*;
  2. import package.classname;
  3. fully qualified name.

import keyword

The import keyword is used to access classes and the interface of another package.

Suppose we have ClassA inside package mypackageA. Now you will see the access to this class in another package in a different way in a further post.

package mypackageA;
public class ClassA{
  public void getMessage(){
  System.out.println("Hello In Package A");
  }
}

Using import packagename.*

If you use an import package.* then all the classes and interfaces of this package will be accessible but not sub-packages.

Here in this example using ClassA from another package that’s what use import mypackageA.* to import all classes and interfaces on this package.

package mypackageB;
import mypackageA.*
public class ClassB{
public static void main(String[]args)
{
   ClassA obj = new ClassA();
   obj.getMessage();
   }
}

Note: This way of import definitely reduces the line of import statement but tries to avoid using it because if the declared package in having lots of classes and interfaces then it will load all. Definitely, it will impact your performance.

Using import packagename.className

If you import package.classname then only declared a class of mentioned package will be accessible.

In this below case for statement package mypackageA.ClassA only classA in package mypackageA will load.

package mypackageB;
import mypackageA.ClassA
public class ClassB{
public static void main(String[]args)
{
   ClassA obj = new ClassA();
   obj.getMessage();
   }
}

Using the fully qualified name

If you are using the fully qualified name of class or interface on time of declaration of reference object then only declared class of this package will be accessible. Now no need to import statements.
But the problem is you need to use a fully qualified name every time when you are accessing the class or interface.

Note: This way generally preferred when two packages have the same class name for example Date Class is in java.sql and java.util package.

package mypackageB;
public class ClassB{
public static void main(String[]args)
{
   mypackageA.ClassA obj = new mypackageA.ClassA();
   obj.getMessage();
   //another instance need to give full qualified name again.
   mypackageA.ClassA obj1 = new mypackageA.ClassA();
   obj1.getMessage();
   }
}

Now you have learned about package creation, access to another class, compilation and execution of classes. Here you will learn about subpackage and way of creation it.

Java SubPackage

The package within the package is called the subpackage. It should be created to further categorize the package.

Note: If you import a package all the classes and interface of that package excluding subpackage. Hence need to import sub package separately if required.

The standard way of defining a package is domain.company.package for example:

//admin related packages
com.fiot.admin.controller
com.fiot.admin.model
com.fiot.admin.repository
com.fiot.admin.service

//user related packages
com.fiot.user.controller
com.fiot.user.model
com.fiot.user.repository
com.fiot.user.service

In the above packages you can easily understand the code layer and modules and when you need to understand the code you can easily understand it.

As mentioned above builtin packages having related classes with the packages and sub-packages. For Example, Input/Output related classes in java.io package, Server and ServerSocket classes in java.net packages and SQL related classes in java.sql packages.

Example of java Subpackage

package com.fiot.subpackage.example;
public class SimpleSubPackageExample{
 public static void main(String args[]){
    System.out.println("Welcome to My Sub Package");
   }
}
To Compile: javac -d . SimpleSubPackageExample.java
To Run: java com.fiot.subpackage.example.SimpleSubPackageExample
Output:Welcome to My Sub Package

When you compile above program it will create SimpleSubPackageExample.class file inside the folder (current_path/com/fiot/subpackage.example). When running this file you have to mention complete package with the file name as given in the above example.

Move the class file to another drive or directory

Let consider for the above example and want to send this file classes folder in e: drive when compile. We have run as below:

To Compile: current_file_directory> javac -d e:\classes SimpleSubPackageExample.java

To run:
To run the program from the current directory, you need to set the classpath of the directory where the class files reside.


current_directory> set classpath=e:\classes;.;
current_directory> java -classpath com.fiot.subpackage.example.SimpleSubPackageExample

Note: The -classpath switch can be used with javac and java tools.

Ways to load the jar or class files

Java supports two ways to load the class files:

  1. Temporary
    By setting the classpath in the command prompt as mentioned in the above example.
By -classpath switch

Permanent
By setting the classpath in the environment variables

Create the jar file, that contains all the class files and then copying 
the jar file in the jre/lib/ext folder.

How to use static import?

The static import feature introduced in Java 5 to access any static member of a class directly. There is no need to qualify a class name.

Static Import Advantage

Less coding is required: if need to use some static members frequently.

Static import Disadvantage

If you overuse the static import statement, then it creates a problem to understand and maintain code.

Example of Static Import

import static java.lang.System.*;

public class StaticImportExample {
	public static void main(String args[]) {
		// Now no need of write System.out
		out.println("Facing Issues on IT");
		out.println("Learn from Other Experinces");

	}
}

Output

Facing Issues on IT
Learn from Other Experinces

What is the difference between import and static import?

import static import
The import statement allows the java programmer to access classes of a package without package qualification. The static import statement allows accessing the static members of a class without the class qualification.
The import statement provides accessibility to classes and interface. The static import statement provides accessibility to static members of the class.

 

Java: Method Overriding


Method Overriding is a concept that allows a child class to provide a specific implementation of a method that is already provided by one of its parent classes. When a method in a child class has the same name, same parameters or signature and same return type(or sub-type) as a method in its parent class, then the method in the child class is said to override the method in the parent class.

See Also:

Example of Method Overriding

Here print() method having the same signature in parent and child class i.e child class print() method overriding on parent class print() method.

public class Person
{
public void print(String name)
	{
	//some code here
	}
}
public class Employee extends Person
{
	@Override
	public void print(String name)
	{
	//some code here
	}

}

How to execute the overridden method?

Type of the object of a class being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.

  • Parent class object is used to invoke the method of the parent class.
  • A child class object is required to execute the method of the child class.

When should we use the overriding method?

It can be used when combining inheritance with overridden methods, a parent class can define the general form of the methods that will be used by all of its child class.

Ways to implement method overriding or runtime polymorphism?

  1. The access modifier of the overridden method in child class can allow more, but not less. For example, A parent class method with access modifier protected can be made public in child class but not private. if you use private will generate a compile-time error.
  2. a final method can not be overridden.
  3. private methods can not be overridden.
  4. The overriding method must have the same return type (or a subtype of it).
  5. We can call the parent class method in the overriding method using super keyword.
  6. We can not override constructors as parents and child class can never have a constructor with the same name.
  7. Abstract methods in an abstract class or interface are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown.
  8. The presence of a synchronized/strictfp modifier with the method has no effect on the rules of overriding, i.e. it’s possible that a strictfp/synchronized method can override a strictfp/non-synchronized one and vice-versa.
  9. Overriding and Exception-Handling

Rule 1: If the super-class overridden method does not throw an exception, the subclass overriding method can only throw the unchecked exception, throwing checked exception will lead to a compile-time error.

Rule 2: If the super-class overridden method does throw an exception, the subclass overriding method can only throw the same, subclass exception. Throwing parent exception in the Exception hierarchy will lead to a compile-time error. Also, there is no issue if the subclass overridden method is not throwing any exception.
See Also: Method Overloading Exception Handling with Example

  • Static methods can not be overridden(Method Overriding vs Method Hiding)
Super Class Instance Method Super Class Static Method
Sub Class Instance Method   Overrides Generates a compile-time error
Sub Class Static Method Generates a compile-time error Hides

Java: Method Overloading Vs Method Overriding


 

Method Overloading Method Overriding
Method Overloading is about the same function have different signatures. Method Overriding is about the same function, same signature but different classes connected through inheritance.
Method Overloading is a concept of compile-time polymorphism Method Overriding is a concept of run time polymorphism.
Method Overloading Example:

public class Employee
{
	public void print()
	{
	//some code here
	}
	public void print(String name)
	{
	//some code here
	}
	public void print(Employee employee)
	{
	//some code here
	}

}
Method Overriding Example:

public class Person
{
public void print(String name)
	{
	//some code here
	}
}
public class Employee extends Person
{
	@Override
	public void print(String name)
	{
	//some code here
	}

}
See Also: Java Method Overloading in Detail See Also: Java Method Overriding in Detail

See Also:

Java: Method Overloading


Java method overloading allows different methods with the same name, but different signatures. Where the signature can be different by the number of input parameters or type of passing parameters or both.

See Also:

Advantage of method Overloading

  • Don’t need to remember so many method names.

Points to remember about Method Overloading

  1. Method Overloading is related to the concept of compile-time (or static) polymorphism.
  2. Method Overloading possible on the same class.
  3. Method Overloading doesn’t consider the return type of method. If two method signature is the same and only differ in return type then the compiler will show as a duplicate method.
  4. Method Overloading can overload static methods but not based on keyword static only.
  5. Method Overloading can also be done for the main() method.
  6. Java language doesn’t support user-defined operator loading but internally supports operator overloading for example : (+) for concatenation.

Note: (Java 8+)If both methods have the same parameter types, but different return type, then it is not possible.

Ways to do Method Overloading

Method overloading is possible by:

  • Change the number of parameters in methods.
  • Change data types of the parameters in methods.
  • Change Order of the parameters of methods.

How to determine parameter matching in Overloading with different Types?

Parameter matching determines when parameter type is different but to higher type(in terms of range) in the same family.

For Example: suppose passing argument type is int, then check for an overloaded method of type int if not found then check for the data type of higher in the same family( long type if still not found then check for the float data type).

public class Demo {
	//overloaded methods
	public void show(int x) {
		System.out.println("In int " + x);
	}

	public void show(String s) {
		System.out.println("In String " + s);
	}

	public void show(byte b) {
		System.out.println("In byte " + b);
	}

	public static void main(String[] args) {
		byte a = 25;
		Demo obj = new Demo();
		// If will call method with by argument
		obj.show(a);
		obj.show("Facing Issues On IT "); // String
		obj.show(250); // Int
		/*
		 * Since method with char type is not available,
		 * so the data type higher
		 * than char in same family is int
		 */
		obj.show('A');
		/*
		 * Since method with float data type is
		 * not available and so it's higher
		 * data type, so at this step their will
		 * be an compile time error.
		 */
		// obj.show(7.5);
	}
}

Output


In byte 25
In String Facing Issues On IT 
In int 250
In int 65

 

Java: Method Signature


A method signature is part of the method declaration where a signature is a combination of the method name and parameter list. Method signature doesn’t consider return type as part of the signature.

The main reason to emphasis on method Signature is because of method overloading. Java compiler distinguishes between the methods based on the method signature.

See Also:

Method Overloading :
Method overloading provides the ability to write methods with the same name but accept different arguments. Method Overloading is compile-time Polymorphism.

Here is one example of method overloading where add method implements by three ways:

  1. double add(double a, double b)
  2. int add(int a, int b)
  3. double add(int a, int b)

Method signature doesn’t consider return type for method overloading, it will consider method 2 and 3 as a duplicate method and return this compile-time error.

Duplicate method add(int, int) in type MethodSignatureExample

As shown in below screen shot.

Java: Method Signature Example
Java: Method Signature Example

Method Signature Examples

public void getMapLocation(int xPos, int yPos)
{
//method code
}

The method signature in the above example is getMapLocation(int, int). In other words, it’s the method name (getMapLocation) and the parameter list of two integers.

public void getMapLocation(Point position)
{
//method code
}

The Java compiler will allow adding another method because its method signature is different, getMapLocation(Point).

 

Java: super Keyword


In java, super keyword is a reference variable used to refer immediate parent class object.

Whenever, we create an instance of child/subclass, an instance of the parent class created implicitly which referred to a super reference variable.

super keyword use mainly on the below cases:

  • super to refer immediate parent class instance variable.
  • super to invoke the immediate parent class method.
  • super() to invoke immediate parent class constructor.

See Also: Java: this Keyword

Note: In a constructor super() or this() will always be the first statement. If a constructor is not having this() or super() compiler will implicitly add it.

Example of Java super keyword

In this example, you will see highlighted lines and comments to find all uses of the super keyword.

import java.io.Serializable;

public class Person{
    private String name;
    protected String citizenship;

    public Person()
    {
    }

    public Person(String name, String citizenship) {
        super();
        this.name = name;
        this.citizenship = citizenship;
    }

    public void print() {
		System.out.println("Citizen:"+ citizenship + ",Name:" + name);
	}

}
public class Employee extends Person {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}
	public Employee(int employeeId, String name, String department
, String citizen, int salary) {
		// super keyword use to call parent constructor
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

	public void print() {
		System.out.println("Id :" +
+ ", Department :" + department + ", Salary:" + salary );

		//super keyword to access parent class variables
		System.out.println("Citizen:"+super.citizenship);
		//super keyword use to call parent class method
		super.print();
	}
}

 

Java: this Keyword


In Java, this keyword used as a reference variable that refers to the current object. Java this keyword having many uses:

  • this to refer current class instance variable.
  • this to invoke current class method (implicitly)
  • this() to invoke the current class constructor.
  • this to pass as an argument in the method call.
  • this to pass as an argument in the constructor call.
  • this to return the current class instance from the method.

this Keyword: Example

In the highlighted lines, you will see all the ways of using this keyword

public class Employee  {
	private int employeeId;
	protected String name;
    protected String citizenship;
    private  String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen) {
		// this keyword to resolve name ambiguity
		this.name=name;
		this.citizenship=citizen;
		this.employeeId = employeeId;
		this.department = department;
	}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		// this keyword use to call another constructor
		this(employeeId, name, department, citizen);
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

	public void display() {
		// this to call method and pass as argument
		this.print(this);
	}

	public Employee getEmployee(){
		//This keyword to return current object
		return this;
	}

	public void print(Employee employee) {
		System.out.println("Id :" + employeeId + ", Department :" + department
				+ ", Salary:" + salary + ",Citizen:"
				+ citizenship + ",Name:" + name);
	}

}

Java: static Keyword


In Java, static keyword is used for memory management mainly. Static elements below to the class. It can apply with:

  • Static Variable (also known as a class variable)
  • Static Method (also known as a class method)
  • Static Block
  • Static Nested class
  • Static Import

Note: These static variables and method access by class name it doesn’t require any class instance.

Java Static Variable

A variable declares as static is known as static variable or class variable. This variable value would be common among all the instances of class because these variables take memory in the class area only once when the class first loaded.
Advantage: The static variable makes program memory efficient because of saves memory.

static variable.png

static Variable Example

public class Employee {

	int id;
	String name;
	static String organization = "Facing Issues On IT";

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

	public String display() {
		return "Id:" + id + " Name:" + name + " Organization:" + organization;
	}
}
public class StaticVariableTest {

	public static void main(String[] args) {
		Employee e1=new Employee(1,"Saurabh Gupta");
		Employee e2=new Employee(2,"Gaurav Kumar");

		System.out.println(e1.display());
        System.out.println(e2.display());
        //Change Static value
        Employee.organization="Learn from Others Experience";//Print before change
        System.out.println(e1.display());
        System.out.println(e2.display());
	}

}

Output


Id:1 Name:Saurabh Gupta Organization:Facing Issues On IT
Id:2 Name:Gaurav Kumar Organization:Facing Issues On IT
Id:1 Name:Saurabh Gupta Organization:Learn from Others Experience
Id:2 Name:Gaurav Kumar Organization:Learn from Others Experience

Counter Example with instance and static Variable

public class Counter {
	// instance variable count get memory each time when instance get created
	int count = 0;
	// class variable count will get memory once once when class loaded
	static int staticCount;

	public Counter() {
	//increase the value of each count
     count++;
     staticCount++;
     System.out.println("Count :"+count +" Static Count :"+staticCount);
	}
}
public class CounterExample {

	public static void main(String[] args) {
		new Counter();
		new Counter();
		new Counter();
	}

}

Output


Count :1 Static Count :1
Count :1 Static Count :2
Count :1 Static Count :3

Java Static Method

a static keyword with any method is known as a static method or class method.

  • A static method belongs to the class rather than the instance of a class.
  • A static method can be invoked by class names without the need for creating an instance of a class.
  • A static method can access static data variables only change the value of it.

Restrictions for the static method

There are mainly two restrictions for the static method:

  • The static method can not use non-static data member or call the non-static method directly.
  • this and super keyword cannot be used in static context.

Why Java main() method is static?

The static method doesn’t require an object to call because it’s called my Class Name. If the main() method were a non-static method, JVM creates an object first then call a main() method that would be the problem of extra memory allocation.

Java Static Method Example

public class Employee {

	int id;
	String name;
	static String organization = "Facing Issues On IT";

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

	public String display() {
		return "Id:" + id + " Name:" + name + " Organization:" + organization;
	}
	//static method static member only
	public static void change(String org)
	{
		organization=org;
		//these non static member will throw compile time issues.
		//id=5;
		//name="Rajesh";
	}
}

public class StaticMethodTest {

	public static void main(String[] args) {
		Employee e1=new Employee(1,"Saurabh Gupta");
		Employee e2=new Employee(2,"Gaurav Kumar");

		System.out.println(e1.display());
        System.out.println(e2.display());
        //Change Static value by calling static method
        Employee.change("Learn from Others Experience");
        System.out.println(e1.display());
        System.out.println(e2.display());
	}

}

Output


Id:1 Name:Saurabh Gupta Organization:Facing Issues On IT
Id:2 Name:Gaurav Kumar Organization:Facing Issues On IT
Id:1 Name:Saurabh Gupta Organization:Learn from Others Experience
Id:2 Name:Gaurav Kumar Organization:Learn from Others Experience

Java Static Block

  • A static block is executed before the main method at the time of classloading.
  • A static block is used to initialize the static data variables and members.
public class StaticBlockExample {

	static {
		System.out.println("Static block is executed");
	}

	public static void main(String args[]) {
		System.out.println("Main method executed");
	}

}

Output


Static block is executed
Main method executed

Can we execute a program without main() method?

It was possible till JDK 1.6. by executing the static block. Since JDK 1.7, it is not possible to execute a java class without the main method.

class Test{
  static{
  System.out.println("Static block is executed");
  System.exit(0);
  }
}

JDK 1.6


Static block is executed

JDK 1.7


Error: Main method not found in class Test, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Java Static Import

The static import feature introduced in Java 5 to access any static member of a class directly. There is no need to qualify class name.

Static Import Advantage

Less coding is required: if need to use some static member frequently.

Static import Disadvantage

If you overuse the static import statement, then it creates problem to understand and maintain code.

Example of Static Import

import static java.lang.System.*;

public class StaticImportExample {
	public static void main(String args[]) {
		// Now no need of write System.out
		out.println("Facing Issues on IT");
		out.println("Learn from Other Experinces");

	}
}

Output


Facing Issues on IT
Learn from Other Experinces

What is the difference between import and static import?

import static import
The import statement allows the java programmer to access classes of a package without package qualification. The static import statement allows to access the static members of a class without the class qualification.
The import statement provides accessibility to classes and interface. The static import statement provides accessibility to static members of the class.

Java: final Keyword


In Java, the final is keyword use with class, method, and variables. When it combined with one of these having below side effects on compile time:

  • A final class can not be instantiated.
  • A final method can not be overridden.
  • A final variable can not be re-assigned.

See Also: Difference between final, finally and finalize

final keyword Example

A final variable can not be re-assigned.

final variable example
Final Variable can be reassigned

A final class can not be subclassed.

Final Class Example
Final class can not be subclassed

A final method can not be overridden.

Final method Example
final method can not be overloaded

 

Java : java.lang.Object Class & Methods


java.lang.Object  is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. It’s also called as Object Class.

Methods of Object Class

Below are methods of Object Class for different purpose  as below:

  1. protected Object clone() : Creates and return copy of this object.
  2. boolean equals(Object obj) : Indicate weather other object is equal or not.
  3. protected void finalize() : To make object finalize for garbage collection.
  4. Class getClass() : Returns the runtime class of this Object.
  5. int hashCode() : Returns a hash code value of Object.
  6. void notify() : Wakes up a single thread that is waiting on this object’s monitor. It works in multithread env with tow thread only.
  7. void notifyAll() : Wakes up all threads that are waiting on this object’s monitor. if more than one thread running.
  8. String toString() : Returns string representation of object.
  9. void wait() : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
  10. void wait(long timeout) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or specified time has elapsed.
  11. void wait(long timeout, int nanos) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

In this below examples you can see how to override and utilize these methods in different ways.

Example of clone() method

Object class clone() method, create and return copy of a object(). For implementing a clone method class have implements Cloneable interface which is a Marker Interface. There are two ways of cloning of object Shallow Cloning and Deep Cloning. For more detail follow below link.

Java : Shallow and Deep Object Cloning

Eample of finalize() method

Garbage collector calls Object class finalize() method before clean object. We can override this method for code clean-up activity like closing files, database connection and socket. Follow below link to know more about finalize() method example and uses:

Java : Garbage Collection finalize() method example and uses

Example of hashCode(), equals() and toString() method

Override toString() method to print object values. Same way we can override hash() code and equals() method also. hashcode and equals() method have contract as:

“If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals() and not hashCode() your class violates this contract

For example of toString(), hashcode() and equals() follow below link:

Java : How to remove duplicate objects from list?

Example of getClass() method

The getClass() method returns the run time class of an object.  As in below examples returning class name of objects.

import java.util.Calendar;

public class GetClassExample {

	public static void main(String[] args) {
		GetClassExample test=new GetClassExample();

		System.out.println("Class Name :"+test.getClass().getName());

		Calendar calendar=Calendar.getInstance();
		System.out.println("Calendar Class Name :"+calendar.getClass().getName());

		Integer integer=new Integer(10);
		System.out.println("Integer Class Name :"+integer.getClass().getName());

	}
}

Output


Class Name :com.Object.GetClassExample
Calendar Class Name :java.util.GregorianCalendar
Integer Class Name :java.lang.Integer

Example of wait(), notify() and notifyAll() method

Below is example of restaurant using method wait(), notify() and notifyAll(). Where Two waiter thread are running and waiting for  order message when they got order notify will pass the order message and based on available waiter will process order.

public class Order {
    private String msg;
    public Order(String msg){
        this.msg=msg;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String str) {
        this.msg=str;
    }
}

Waiter class that will wait for other threads to invoke notify methods to complete it’s processing. Notice that Waiter thread is owning monitor on Order object using synchronized block.

public class Waiter implements Runnable{
    private Order msg;
    public Waiter(Order msg){
        this.msg=msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            try{
                System.out.println(name+" waiting to get notification at time:"+System.currentTimeMillis());
                msg.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name+" waiter thread got notification at time:"+System.currentTimeMillis());
            //process the order now
            System.out.println(name+" processed: "+msg.getMsg());
        }
    }
}

Here notification thread will call notify() method on order message so that available waiter will pick the order.Notice that synchronized block is used to own the monitor of Order object.

public class Notification implements Runnable {
    private Order msg;
    public Notification(Order msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name+" started");
        try {
            Thread.sleep(1000);
            synchronized (msg) {
                msg.setMsg(name+" Notification work done");
                msg.notify();
                //use notify all when lots of thread are running
                // msg.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Below test class having multiple threads of Waiter and notification to execute order.

public class WaitNotifyExample {
	public static void main(String[] args) {
		Order order= new Order("My Order");
	        Waiter waiter1 = new Waiter(order);
	        new Thread(waiter1,"waiter 1").start();

	        Waiter waiter2 = new Waiter(order);
	        new Thread(waiter2, "waiter 2").start();

	        Notification notification = new Notification(msg);
	        new Thread(notification, "notification").start();
	        System.out.println("All the threads are started");
	}
}

When we will execute the above program, we will see below output but program will not complete because there are two waiter threads waiting for Order object and notify() method has wake up only one of them, the other waiter thread is still waiting to get notified.

Output


waiter 2 waiting to get notification at time:1552127934935
waiter 1 waiting to get notification at time:1552127934935
notification started
All the threads are started
waiter 2 waiter thread got notification at time:1552127935946
waiter 2 processed: notification Notification work done

or


waiter 1 waiting to get notification at time:1552127972873
All the threads are started
notification started
waiter 2 waiting to get notification at time:1552127972873
waiter 1 waiter thread got notification at time:1552127973876
waiter 1 processed: notification Notification work done

Conclusion

Here you learn about the Object class and it’s methods. How to use these objects class methods with example and where can we use that.

References

https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html

Java : Shallow and Deep Object Cloning


Pr-requisite : Marker Interface in Java and Use, CloneNotSupportedException

In object oriented programming object copy or copy of object are possible many ways like copy constructor or copy of object. Here we will focus on both the ways for copy of object.

  • Shallow Copy or Shallow Cloning
  • Deep Copy or Deep Cloning

See also : Java : Shallow Cloning Vs Deep Cloning

Example of Shallow Cloning and Deep Cloning
Java : Shallow Cloning and Deep Cloning

Shallow Copy or Shallow Cloning

Whenever we use default implementation of copy of object means it create new instance of object and copies all the fields to the object new fields and if fields are non primitive or reference type variable to copy to new fields as reference of that non-primitive fields.

clone() method by default support shallow copy of object().  for implementing clone() method you have to implement Cloneable interface which is marker interface.

Shallow copy example by constructor

import java.util.Arrays;

public class Courses {
	String[] courseArr;
	// Shallow copy by constructor because in copy taking reference of object
	public Courses(String[] courseArr) {
		super();
		this.courseArr = courseArr;
	}
	@Override
	public String toString() {
		return "Courses [courseArr=" + Arrays.toString(courseArr) + "]";
	}

	public static void main(String[] str) {
	String[] courseArr = { "Math", "Physics", "Chemistry", "Hindi", "English" };
	Courses courses = new Courses(courseArr);
	System.out.println(courses);
	courseArr[2] = "Computer";//while changing in passed object will reflect on copy of object
	System.out.println(courses);
	}
}

Output


Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]
Courses [courseArr=[Math, Physics, Computer, Hindi, English]]

Shallow copy by clone method

In this example doing  shallow copy by clone method default way by implementing Cloneable interface and overriding clone() method which will by default make copy of object but here sub object course field in Student object will take reference of copied student object. It means if make any change on course object values will reflect same on copy object. clone method will always throw CloneNotSupportedException which always need to handle.

class Courses {
	String course1;
	String course2;
	String course3;

	public Courses(String course1, String course2, String course3) {
		this.course1 = course1;
		this.course2 = course2;
		this.course3 = course3;
	}
}

class Student implements Cloneable {
	int id;
	String name;
	Courses courses;

	public Student(int id, String name, Courses courses) {
		this.id = id;
		this.name = name;
		this.courses = courses;
	}

	// Default version of clone() method. It creates shallow copy of an object.
	// CloneNotSuportedException is checked exception always need to handle that
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

public class ShallowCopyInJava {
	public static void main(String[] args) {
		Courses science = new Courses("Physics", "Chemistry", "Math");
		Student student1 = new Student(1020, "Saurabh", science);
		Student student2 = null;

		try {
			// Creating a clone of student1 and assigning it to student2
			student2 = (Student) student1.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

		// Printing the subject3 of 'student1'
		System.out.println(student1.courses.course3); // Output : Maths

		// Changing the course3 of 'student2'
		student2.courses.course3 = "Biology";

		// This change will be reflected in original student 'student1'
		System.out.println(student1.courses.course3); // Output : Biology
	}
}

Output


Math
Biology

Note: If class is having only primitive type values or Immutable object there is no difference between Shallow and Deep Cloning of object.

Deep Copy or Deep Cloning

Whenever we need own copy not to use default implementation (shallow copy or shallow cloning) of object. Always implement according to our need and make sure all the member of  class also having deep copied of fields.

If using cloneable interface and overriding clone() method of object class make sure member objects /reference objects also having deep copy of fields.

Deep copy example by constructor

import java.util.Arrays;

public class Courses {
	String[] courseArr;

	// Deep copy object because copy actual fields value not references
	public Courses(String[] courseArr) {
		super();
		if (courseArr != null) {
			this.courseArr = new String[courseArr.length];
			for (int i = 0; i <courseArr.length; i++) {
				this.courseArr[i] = courseArr[i];
			}
		}
	}

	@Override
	public String toString() {
		return "Courses [courseArr=" + Arrays.toString(courseArr) + "]";
	}

	public static void main(String[] str) {
		String[] courseArr = { "Math", "Physics", "Chemistry", "Hindi", "English" };
		Courses courses = new Courses(courseArr);
		System.out.println(courses);
		courseArr[2] = "Computer";// while changing in passed object will reflect on copy of object
		System.out.println(courses);
	}
}

Output


Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]
Courses [courseArr=[Math, Physics, Chemistry, Hindi, English]]

Deep copy by clone method
In this example doing  deep copy by clone method but handle copying each individual reference object copy separately as in Student class clone() method. It means if make any change on course object values will not reflect same on copy object. clone method will always throw CloneNotSupportedException which always need to handle.

class Courses implements Cloneable{
String course1;
String course2;
String course3;

public Courses(String course1, String course2, String course3) {
this.course1 = course1;
this.course2 = course2;
this.course3 = course3;
}

protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}

class Student implements Cloneable
{
int id;
String name;
Courses courses;

public Student(int id, String name, Courses courses)
{
this.id = id;
this.name = name;
this.courses = courses;
}

//Overriding clone() method to create a deep copy of an object.
//CloneNotSuportedException is checked exception always need to handle that

protected Object clone() throws CloneNotSupportedException
{
Student student = (Student) super.clone();
student.courses = (Courses) courses.clone();
return student;
}
}

public class DeepCopyInJava
{
public static void main(String[] args)
{
Courses science = new Courses("Physics", "Chemistry", "Math");
Student student1 = new Student(1020, "Saurabh", science);
Student student2 = null;

try
{
//Creating a clone of student1 and assigning it to student2
student2 = (Student) student1.clone();
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}

//Printing the subject3 of 'student1'
System.out.println(student1.courses.course3); //Output : Math
//Changing the subject3 of 'student2'
student2.courses.course3 = "Biology";
//This change will not be reflected in original student 'student1'
System.out.println(student1.courses.course3); //Output : Math
}
}

Output


Math
Math

Conclusion

Here you learn about Shallow and Deep copy  of object by constructor and implementing by clone() method of Cloneable Interface which is marker interface.

Java : Immutable Class/Collection Creation


What is Mutable/Immutable Class?

A class is called as immutable class once object is created , we can not change it’s fields/objects values. If values are changeable then it’s mutable class.

Designing Rule

Classes should be immutable unless there’s a very good reason to make them mutable….
If a class cannot be made immutable, limit its mutability as much as possible.

In java all the wrapper classes and String class is immutable. For Ex: immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc.

How to make a class Immutable Class?

Below are step by step guide to make a class Immutable:

Step 1 : Don’t provide “setter” methods that modify fields or objects referred to by fields.
Step 2 : Make all fields final and private.
Step 3 : Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
Step 4 : If the instance fields include references to mutable objects, don’t allow those objects to be changed: Don’t provide methods that modify the mutable objects.
Step 5 : Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor.
If necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

What are Benefits of Immutable Object?

  1. Immutable objects are thread-safe so you will not have any synchronization issues.
  2. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
  3. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
  4. Immutability makes it easier to parallelize your program as there are no conflicts among objects.
  5. Immutable objects internal state of your program will be consistent even if you have exceptions.
  6. References to immutable objects can be cached as they are not going to change.

How to create Immutable Lists, Sets or Maps?

In JAVA 8 added “unmodifiable” method and JAVA 9 added “of” factory method to make collections like lists, sets and maps as immutable.  for example :

JAVA 8


Unmodifiable List
List stringList = Arrays.asList("Facing", "Issues", "On", "IT");
stringList = Collections.unmodifiableList(stringList);

Unmodifiable Set
Set stringSet = new HashSet<>(Arrays.asList("Facing", "Issues", "On", "IT"));
stringSet = Collections.unmodifiableSet(stringSet);

Unmodifiable Map
Map<String,Integer> stringMap = new HashMap<String, Integer>();
stringMap.put("Facing",1);
stringMap.put("Issues",2);
stringMap.put("On",3);
stringMap.put("IT",4);
stringMap = Collections.unmodifiableMap(stringMap);

JAVA 9


Unmodifiable List
List stringList = List.of("Facing", "Issues", "On", "IT");
Unmodifiable Set
Set stringSet = Set.of("Facing", "Issues", "On", "IT");

Unmodifiable Map
Map stringMap = Map.of("Facing",1, "Issues",2, "On",3, "IT",4);

 

Immutable Class Example


//make class final so that method not override
public final class ImmutableClass {
	final String pancardNumber;
	final String aadharNumber;
	final DOB dob;

	// Create object
	public ImmutableClass(String pancardNumber, String aadharNumber, DOB dob) {
		this.pancardNumber = pancardNumber;
		this.aadharNumber = aadharNumber;
		this.dob = dob;
	}
    //No setter method so that no fields get modifiable
	public String getPancardNumber() {
		return pancardNumber;
	}

	public String getAadharNumber() {
		return aadharNumber;
	}

	@Override
	public String toString() {
		return "ImmutableClass [pancardNumber=" + pancardNumber + ", aadharNumber=" + aadharNumber + ", dob=" + dob
				+ "]";
	}
}
public class  DOB {
	private int day;
	private int month;
	private int year;
	public DOB(int day, int month, int year)
	{
	this.day=day;
	this.month=month;
	this.year=year;
	}

	public int getDay() {
		return day;
	}

	public int getMonth() {
		return month;
	}

	public int getYear() {
		return year;
	}

	@Override
	public String toString() {
		return "DOB [day=" + day + ", month=" + month + ", year=" + year + "]";
	}

}
public class ImmuTableClassTest {

	public static void main(String[] args) {
		DOB dob = new DOB(24, 04, 1992);
		ImmutableClass immutableClass = new ImmutableClass("ABCD12345", "1234567890123456", dob);
		System.out.println(immutableClass);

	}

}

Output


ImmutableClass [pancardNumber=ABCD12345, aadharNumber=1234567890123456, dob=DOB [day=24, month=4, year=1992]]

Conclusion

In this blog you understand below points:

  • What is mutable and Immutable classes?
  • How make a class Immutable?
  • How to make collections like Lists, Sets and maps  immutable by Java 8 and Java 9?
  • Immutable class example.

References

https://docs.oracle.com/javase/9/core/creating-immutable-lists-sets-and-maps.htm