Methods in Object class

As known java.lang.Object is base class, of all classes in Java.

Below are the methods of Object class, that means each and every object can invoke below methods.

Method Declaration Method Details
1 protected Object clone() creates a copy of current object, and returns
2 boolean equals(Object obj); This method returns whether the object(sent as parameter) is equal to invoking object.
3 protected void finalize(); When there are no more references to the object, garbage collector, may invoke this method.(This method acts just like destructor of the c plus plus class)
4 Class getClass(); returns runtime class of the invoking.
5 int hashCode(); returns unique hash code value of invoking object. This is used to uniquely identify each object.
6 final void notify(); wakes up single thread that is waiting on this object’s monitor.
7 final void notifyAll(); wakes up all threads that are waiting on this object’s monitor.
8 String toString(); returns string representation of invoking object.
9 void wait(); causes current thread to wait until another thread invokes notify() or notifyAll() method for this object.
10 void wait(long timeout_millis); causes current thread to wait until either another thread invokes the notify() or notifyAll() method for this object, or specified amount of time(sent as parameter) has been elapsed.
11 void wait(long timeout_millis, int timeout_nanos); causes current thread to wait until another thread invokes notify() or notifyAll() method for theobject, or some other thread interrupts the current thread, or a certain amount of real time(sent as parameters) has been elapsed.

final methods in Object class

Below are final methods in Object class
getClass(), wait(), wait(long), wait(long,int), notify(), notifyAll() methods are final, and cannot be overridden.

Below non final methods can be overridden.
clone(), equals(), hashCode(), toString() methods are non final, and can be overridden by any class

Below is an example showing that java.lang.Object is Base class

class Test{

}

public class ObjectSuperClass {
	public static void main(String args[])
	{
	Test obj = new Test();
	Class c = obj.getClass();
	Class sc = c.getSuperclass();

	System.out.println("Super class of Test is: "+sc.getName());
	}
}

Output:
Super class of Test is: java.lang.Object

Also note that instance of java.lang.Object class can be created.

No class can exist in Java, which is not Derived class of Object class. All Java classes, by default inherit from java.lang.Object class.

An object of java.lang.Object class, can refer to any object in Java.
Since Object is base class of all classes, Conversion of any object to String, checking for equality of objects, etc… is being supported by each and every object in Java

You may also like to read:
Can we have static method in abstract class
How many types of inheritance in Java
How to implement Adapter pattern using inheritance

Access Specifier and Scope

Below are Access Specifiers supported in Java.
1. private
2. public
3. protected
4. default or none

private, public, protected are Access specifiers, which can be used only for members(data members and member methods) of a class.

private members can be accessed only within the class.

public members can be accessed with the class, other classes in current package, classes in other package.

protected members can be accessed within the class, and in the immediate derived class.

members with no access specifiers can be accessed within the class, and other classes only within current package.

Lifetime of variables

Lifetime of a variable, depends on the place where it has been declared.

Life time of Data members or instance variables is same as the object, in which they exist. An object is destroyed by garbage collector Java when there are no more reference to that object.

Local Variables:
Local variables are the variables declared in the method body. Local variable are available within method body until method returns.

Arguments or Parameters:
Arguments or Parameters are passed to constructor or methods, and are available until the constructor or method returns.

Also variables can be declared in a block(Eg. if, else block,etc…), within a method. Such variables are available only within the block where they have been declared.

Below is an example code snippet:

class Test1
{
	int i,j; //data members or member variables or instance variables

	Test1()//constructor
	{
	i = 20;
	j = 11;

	System.out.println("Test1() Constructor");
	}

	void add() //member methods
	{
	int k; //local variable i..e not a member variable of Test1 class
	//NOTE: k cannot be accessed from object of Test1 class
	k = i+j;
	System.out.println("Add Result is:"+k);
	}

	void sub()
	{
	int l = i-j; //l is local variable
	System.out.println("Sub Result is:"+l);
	}
}

public class ClassDemo {
//execution starts from here
public static void main(String args[])
{
//obj is local object
	Test1 obj; //declaring object reference
	obj=new Test1(); //creating object of Test1 class
	obj.add(); //invoking add() method of Test1 class, using object obj

	obj.sub();
}
}

You may also like to read:
purpose of static block
what is for each loop, in java

static method in Abstract class

Can a static method be a member of Abstract Class?

Read here for What is a abstract method? and what is abstract class?

static method is associated with class and not with individual objects of the class.

Yes, an abstract class can have static methods. But a static method cannot be abstract.

Also remember that, static methods take part in inheritance.
But static methods do not take part in polymorphism.

Below example shows that an abstract class, can have static method.


abstract class Abs1{
	int i,j;
	Abs1(){
		super();
		System.out.println("Abs1() Constructor");
	}

	Abs1(int i, int j)
	{
		this();
		this.i = i;
		this.j = j;
		System.out.println("Abs1(int i, int j) Constructor");
	}

	public static void met1()
	{
		System.out.println("met1() method in Abs1 class");
	}
}

public class AbstractDemo extends Abs1{

	AbstractDemo(){
		System.out.println("AbstractDemo() Constructor");
	}
	public static void main(String args[])
	{
		AbstractDemo obj = new AbstractDemo();
		System.out.println("in main() method");

		Abs1.met1();
	}
}

You may also like to read:
Difference between static and non static block
how many keywords or reserved words in java
purpose of static inner class

Difference between Anonymous object and anonymous class

Below is an example of Anonymous object.
Anonymous object is an object without name. Generally anonymous object is used when only one method need to be invoked with the object, and invoking methods with the created object may not be further required in the program.

class InnerDemo
{
	void show(){
		System.out.println("show() in InnerDemo class");
	}
}

public class AnonymounsInnerClassObject {
	public static void main(String args[])
	{
		new InnerDemo().show();
	}
}

Anonymous Inner class is a class which does not have name, however there are some constraints like explicit constructor cannot be used with Anonymous Inner class.

Anonymous object or named object can be created using an Anonymous class.

Below is an example of creating Anonymous object of Anonymous class.

class InnerClass{

	public void met1()
	{
		System.out.println("met1() in InnerClass");
	}
}

public class AnonymousObj1 {
	public static void main(String args[])
	{
		new InnerClass(){
			public void met1(){
				System.out.println("met1() in Anonymous class");
			}
		}.met1();
	}
}

Below is an example of creating named object of Anonymous class.

class InnerClass1{

	public void met1()
	{
		System.out.println("met1() in InnerClass1");
	}
}

public class NamedObj {
	public static void main(String args[])
	{
		InnerClass1 obj = new InnerClass1(){
			public void met1(){
				System.out.println("met1() in Anonymous class");
			}
		};

		obj.met1();
	}
}

You may also like to read:
What is static inner class?
Create Thread by extending anonymous class from Thread class
What is inner interface?

Create Thread using Anonymous inner class

As briefed, a Thread is light weight process.

Below is an example, on how to create and start Thread, using Anonymous inner class.

Create Anonymous inner class, which extends from java.lang.Thread and override public void run() method.

public class ThreadAnonymousInnerClass {
	public static void main(String args[])
	{
		Thread t1=new Thread(){
		public void run(){
		for(int i=0;i<=10;i++){
		try{
		System.out.println("Thread t1: "+i);
		Thread.sleep(100);  //100 milliseconds
		}catch(InterruptedException e){
		System.out.println("Exception:"+e.getMessage());
		}
		}
		}
		};

		t1.start();

		for(int i=0;i<=10;i++){
		try{
		System.out.println("Main Thread: "+i);
		Thread.sleep(100);  //100 milliseconds
		}catch(InterruptedException e){
		System.out.println("Exception:"+e.getMessage());
		}
		}
	}
}

Create Anonymous class by implementing Runnable interface

How to create Thread, using anonymous class for Runnable. In below example, we are creating object of an anonymous class which implements Runnable interface.

public class ThreadAnonymousRunnable {
	public static void main(String args[])
	{
		new Thread( new Runnable() {
		    public void run() {

              for(int i=0;i<10;i++)
    	      {
    		System.out.println("child_thread: "+i);
    		try
    		{
    			Thread.sleep(100);
    		}catch(InterruptedException ie){
    			System.out.println(ie.getMessage());
    		}
    	     }
		    }
		}).start();

		for(int i=0;i<10;i++)
    	        {
    		System.out.println("main_thread: "+i);
    		try
    		{
    			Thread.sleep(100);
    		}catch(InterruptedException ie){
    			System.out.println(ie.getMessage());
    		}
    	        }
	}
}

Further reducing size of code

public class ThreadAnonymousRunnable {

	private static void thread_body(String thread_name)
	{
		for(int i=0;i<10;i++)
    	{
    		System.out.println(thread_name+": "+i);
    		try
    		{
    			Thread.sleep(100);
    		}catch(InterruptedException ie){
    			System.out.println(ie.getMessage());
    		}
    	}
	}

	public static void main(String args[])
	{
		new Thread( new Runnable() {
		    public void run() {

		    	thread_body("child_thread");
		    }
		}).start();

		thread_body("main_thread");
	}
}

You may also like to read:
purpose of synchronized keyword
how to use synchronized with a class
how to use synchronized with a method
what are concurrent collections

Different Types of Inheritance in Java

Inheritance is one of the powerful Object Oriented Concept, and improves re usability of the code.

Below are different types of inheritance
1. Single Inheritance or Simple Inheritance
This is simplest form of Inheritance, in which one class inherits members of another class. In Single Inheritance there exists one Base class and one Derived class.

Single Inheritance in Java
Single Inheritance

2. Multilevel Inheritance
In Multilevel inheritance, a Derived class is a Base class for some other class. As shown in below example class B is Derived from class A. And further class C is derived from class B. And class C can further be Base class of some other class, and there can be few more levels. Multilevel Inheritance example
multi level inheritance
multi level inheritance

Having too many Levels may adversely affect performance during run time.

Refer Inheritance in Generic class.

3. Hierarchical Inheritance
In Multilevel Inheritance, there is common Base class for more than one Derived class.
As shown in below picture class A is common Base class to classes B and C. Hierarchical Inheritance example

4. Hybrid Inheritance
Hybrid Inheritance has more than one inheritance. Actually this is combination of Multilevel, Single and Hierarchical Inheritance. Below is Hybrid Inheritance Example

Hybrid Inheritance in Java
Hybrid Inheritance in Java

You may also like to read:
Why multiple inheritance is not supported in Java?

Difference between Composition and Aggregation

In Object oriented languages, Composition, Aggregation and Inheritance are the most common relationships exist between classes.

Composition in Java

Composition is has-a relationship. Also sometimes referred as non-separable part of the whole.
Composition is more stronger relationship compared to Aggregation. Here composed object cannot exist without composing object, and both objects have same life time.

As shown in below code snippet, object of B(i..e obj) cannot exist without object of B. Object of B gets created only along with object of A. Also obj1 does not continue to exist, after object of A gets destroyed.

class A{
B obj;
//… other data members and methods, of class A
}

Aggregation

Aggregation is also a has-a relationship. Also sometimes referred as separable part to whole.
Aggregation is a weaker relationship compared to Composition.
As shown in below code snippet, object of D(i..e obj1) can exist even before object of C gets created. Also obj1 may continue to exist even after object of C is destroyed.

class C{
D obj1;
//… other data members and methods, of class C
}
Composition is Strong Has-A relationship Aggregation is a Weak Has-A relationship.

To understand difference between Composition and Aggregation, lets us take an example of a College with few Departments, and each Department with Lecturers.

aggregation and composition
aggregation and composition

Relationship between College and Department is Composition, and relationship between Department and Lecturer is Aggregation.

class College
{
  private List depts;

  public College()
  {
    depts.add(new Department("Computer Dept"));
    depts.add(new Department("Electrical Dept"));
    depts.add(new Department("Electronics Dept"));
  }

  //...other methods in College class
}

A Department cannot exist without College, hence difference between them is Strong and hence Composition.
When College no more exist, Department cannot exist.

Relationship between Department and Lecturer can be Aggregation, as it is weaker. A Lecturer can exist, even before Department exist. And Lecturer may continue to exist even after Department gets destroyed.

class Department
{
  private Lecturer my_obj;

  public void setLecturer(Lecturer lect)
  {
    my_obj = lect;
  }
  //...other methods in Department class
}

Adapter Pattern with Inheritance

Adapter pattern makes two incompatible interfaces to work together. These Incompatible interfaces are not designed and developed for one another, and assuming they have evolved separately.

Adapter Pattern can be implemented using any of the below.

  1. Inheritance
  2. Composition

Implementing Adapter pattern with Inheritance

In below example NewArithmetic and Arithmetic are classes, which are incompatible. And they have been designed separately, and one is not designed for another.

Now ArithmeticAdapter is implemented to make NewArithmetic and Arithmetic classes, compatible with each other.

Here ArithmeticAdapter inherits from Adaptee, i..e NewArithmetic

public class NewArithmetic
{
    public float add_values(float val1, float val2)
    {
        return val1+val2;
    }

    public float sub_values(float val1, float val2)
    {
        return val1-val2;
    }
}

public class ArithmeticAdapter extends NewArithmetic{
    public int add_adptr(int val1, int val2)
    {
        return (int)add_values(val1,val2);
    }

    public int sub_adptr(float val1, float val2)
    {
        return (int)sub_values(val1,val2);
    }
}

public class Arithmetic
{
    public void add(int val1,int val2)
    {
        System.out.println("Added Result:"+new ArithmeticAdapter().add_adptr(val1, val2));
    }

    public void sub(int val1,int val2)
    {
        System.out.println("Subtraction Result:"+new ArithmeticAdapter().sub_adptr(val1, val2));
    }
}

public class AdapterPattern {
    public static void main(String[] args) {
        Arithmetic obj = new Arithmetic();

        obj.add(23, 42);
        obj.sub(46, 21);
    }

}

Output:
Added Result:65
Subtraction Result:25

You may also like to read: Adapter Pattern with Composition

Hierarchical Inheritance

In Hierarchical Inheritance, there is common Base class for more than one derived class. Below is an Example of Hierarchical Inheritance

class A8
{
	public A8(int i)
	{
		System.out.println("A8() constructor:"+i);
	}

	public void show()
	{
		System.out.println("show() in A8");
	}
}

class B8 extends A8
{
	public B8()
	{
		super(0);
		System.out.println("B8() constructor");
	}

	public void met1()
	{
		System.out.println("met1() in B8");
	}
}

class C8 extends A8
{
	public C8()
	{
		super(20);
		System.out.println("C8() constructor");
	}

	public void met2()
	{
		System.out.println("met2() in C8");
	}
}

public class HierarchicalInheritance {
public static void main(String args[])
{
	B8 obj = new B8();
	System.out.println();
	C8 obj1 = new C8();

	obj.show();
	obj.met1();

	obj1.show();
	obj1.met2();
}
}


Output:
A8() constructor:0
B8() constructor

A8() constructor:20
C8() constructor
show() in A8
met1() in B8
show() in A8
met2() in C8

You may also like to read:
Java Multilevel Inheritance
What is final class

How to override toString() Method

As known Object class is base class of all classes in Java. Object class provides some methods, which are useful for each and every Java class. Among the methods provided by Object class toString() is one of the important method.

Below is declaration of toString() method
public String toString();

Below is an example showing how to override toString()

//Overriding toString() method
class A2{
	int i,j;

	public A2(int i,int j)
	{
		this.i = i;
		this.j = j;
	}
	
//toString() actually is being implemented in Object class
	public String toString()
	{
		return " "+i+" "+j;
	}

}


public class OverrideToString {
public static void main(String args[])
{
	A2 oa = new A2(10,20);
	System.out.println("Check Value:"+oa.toString());
}
}

Output:
Check Value: 10 20

Output of above program, on commenting toString() implementation in A1 class:
Check Value:A2@1f33675

You may also like to read: Difference between String and String Builder