See the Tutorial List

Concept of Object and Classes in Java

Since Java is an object oriented language, complete java language is build on classes and object. Java is also known as a strong Object oriented programming language(OOPS).

OOPS is a programming approach which provides solution to problems with the help of algorithms based on real world. It uses real world approach to solve a problem. So object oriented technique offers better and easy way to write program then procedural programming model such as C, ALGOL, PASCAL.


Main Features of OOPS

  • Inheritence
  • Polymorphism
  • Encapsulation
  • Abstraction

As an object oriented language Java supports all the features given above. We will discuss all these features in detail later.


Java Class

In Java everything is encapsulated under classes. Class is the core of Java language. Class can be defined as a template/ blueprint that describe the behaviors /states of a particular entity. A class defines new data type. Once defined this new type can be used to create object of that type. Object is an instance of class. You may also call it as physical existence of a logical template class.

A class is declared using class keyword. A class contain both data and code that operate on that data. The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods. Thus, the instance variables and methods are known as class members. class is also known as a user defined datatype.

A class and an object can be related as follows: Consider an ice tray(like of cube shape) as a class. Then ice cubes can be considered as the objects which is a blueprint of its class i.e of ice tray.


Rules for Java Class

  • A class can have only public or default(no modifier) access specifier.
  • It can be either abstract, final or concrete (normal class).
  • It must have the class keyword, and class must be followed by a legal identifier.
  • It may optionally extend one parent class. By default, it will extend java.lang.Object.
  • It may optionally implement any number of comma-separated interfaces.
  • The class's variables and methods are declared within a set of curly braces {}.
  • Each .java source file may contain only one public class. A source file may contain any number of default visible classes.
  • Finally, the source file name must match the public class name and it must have a .java suffix.


A simple class example

Suppose, Student is a class and student's name, roll number, age will be its property. Lets see this in Java syntax

class Student.
{
 String name;
 int rollno;
 int age;
}

When a reference is made to a particular student with its property then it becomes an object, physical existence of Student class.

Student std=new Student();
After the above statement std is instance/object of Student class. Here the new keyword creates an actual physical copy of the object and assign it to the std variable. It will have physical existence and get memory in heap area. The new operator dynamically allocates memory for an object

creation of object in java


Private and final methods

One confusing question always arrives that, why private methods are not declared always as final and do the compiler treats private methods as final?

In java, if a method is private or it is final then it can not be overridden by the subclasses. So if a method is declared as private then it is unnecessary to make it final. But declaring a method as private and final does not cause any problem. Also, private methods are automatically considered as final. The second question “does the compiler treats private methods as final”. Yes, the compiler treats private methods as final because the compiler does not allow a private method to override and it also safe the subclasses for overriding final method.

Syntax to declare a method as private and final

	
class Studytonight
{ 
   private final void xyz() 
{
	-----
	-----
	-----
	-----

} 
}
	

Example:

	
public class PrivateFinalDemo2
{
   private void abc() 
	{
	System.out.println("*****Parent class executed*****");
	}
   public static void main(String[] args) 
	{
      PrivateFinalDemo2 obj = new PrivateFinalDemo3();
obj.abc();
      PrivateFinalDemo3 obj1 = new PrivateFinalDemo3 ();
obj1.abc();
	}
}
class PrivateFinalDemo3 extends PrivateFinalDemo2
{
   public void abc()
	{
System.out.println("*****Child class executed*****");
	}
}
	

private-final-method

Below is an example in which compiler time error will occur "private access in Base".

Example:

	
class PrivateFinalDemo{
    private final void xyz() {} 
} 

class PrivateFinalDemo1 extends PrivateFinalDemo{
    public void xyz() {}  
} 

public class Main { 
    public static void main(String args[]) { 
PrivateFinalDemoobj = new PrivateFinalDemo1(); 
obj.xyz(); 
    } 
}
	

private-final-method


Clone() Method

In Java, cloning an object means to create a copy of an object. The copied object has a new instance object and all initialized field with the contents. An assignment operator is used for creating a copy of the reference variable.

Below is an example in which new reference variable obj1 is created which is pointing to address as obj which is same.

Example:

	
class Add
{ 
int x, y; 
Add() 
	{ 
		x = 10; 
		y = 30;
	} 
} 
class CloneDemo1
{ 
    public static void main(String[] args) 
    { 
        Add obj = new Add(); 
	System.out.println("Object 1");
	System.out.println("**********************");
	System.out.println("X = "+obj.x);
	System.out.println("Y = "+obj.y);
	int z = obj.x + obj.y;
System.out.println("Total = "+z);
	System.out.println("**********************");
	System.out.println("**********************");
	Add obj1 = obj;
	obj1.x=20;
	obj1.y=5;
	System.out.println("Object 2");
	System.out.println("X = "+obj1.x);
	System.out.println("Y = "+obj1.y);
	int z1 = obj1.x + obj1.y;
System.out.println("Total = "+z1);
	System.out.println("**********************");
    } 
    public static void change(Add obj) 
    {  
obj.x = 10; 
	obj.y = 10;
    } 
}
	

clone-method

Below is an example of shallow copy using the clone() method. Shallow copy is the collection of only structure.

Example:

	
import java.util.ArrayList; 
class Mult
{ 
int x, y; 
} 
class Mult2 implements Cloneable
{ 
int a; 
int b; 
Mult c = new Mult(); 
    public Object clone() throws CloneNotSupportedException
    { 
        return super.clone(); 
    } 
} 
public class ShallowCopyDemo
{ 
    public static void main(String args[]) throws CloneNotSupportedException
    { 
       Mult2 obj1 = new Mult2(); 
       obj1.a = 5; 
       obj1.b = 10; 
       obj1.c.x = 15; 
obj1.c.y = 20; 
       Mult2 obj2 = (Mult2)obj1.clone(); 
       obj2.a = 25; 
       obj2.c.x = 30; 
System.out.println(obj1.a + " ==> " + obj1.b + " ==> " + obj1.c.x + " ==> " + obj1.c.y);
System.out.println("*************************"); 
System.out.println(obj2.a + " ==> " + obj2.b + " ==> " + obj2.c.x + " ==> " + obj2.c.y); 
    } 
}
	

clone-method

Below is an example of Deep copy using the clone() method. Deep copy is the collection of a structure as well as the elements.

Example:

	
import java.util.ArrayList; 
class Mult
{ 
int x, y; 
} 
class Mult2 implements Cloneable
{ 
int a; 
int b; 
Mult c = new Mult(); 
    public Object clone() throws CloneNotSupportedException
    { 
        Mult2 obj = (Mult2)super.clone(); 
	obj.c=new Mult();
	return obj;
    } 
} 
public class DeepCopyDemo
{ 
    public static void main(String args[]) throws CloneNotSupportedException
    { 
       Mult2 obj1 = new Mult2(); 
       obj1.a = 5; 
       obj1.b = 10; 
       obj1.c.x = 15; 
obj1.c.y = 20; 
       Mult2 obj2 = (Mult2)obj1.clone(); 
       obj2.a = 25; 
       obj2.c.x = 30; 
System.out.println(obj1.a + " ==> " + obj1.b + " ==> " + obj1.c.x + " ==> " + obj1.c.y);
System.out.println("*************************"); 
System.out.println(obj2.a + " ==> " + obj2.b + " ==> " + obj2.c.x + " ==> " + obj2.c.y); 
    } 
}
	

clone-method-deep-copy


Q. How a class is initialized in java?

A Class is initialized in Java when an instance of class is created using either new operator or using reflection using class.forName(). A class is also said to be initialized when a static method of Class is invoked or a static field of Class is assigned.


Q. How would you make a copy of an entire Java object with its state?

Make that class implement Cloneable interface and call clone() method on its object. clone() method is defined in Object class which is parent of all java class by default.