top
April flash sale

Search

Java Tutorial

Classes and objects are fundamental ideas of object-oriented programming that revolve around the entities of actual life. Object − Objects have behaviours and states. Example: A dog has states- colour, name, race and behaviour-wagging the tail, barking, eating. An object is a class instance.  Class − A class can be described as a template / blueprint describing the behaviour / state supported by the object of its type. An object is a specimen of a class. Software objects are often used to model real-world objects you find in everyday life. A class is a blueprint or prototype defined by the user that creates objects from. It reflects the collection of characteristics or techniques prevalent to all single type objects. These elements that can generally be included in class declarations are listed below: Body: The body of the class encircled by braces, { }. Class name: The class name means name of class declared. Class name and file name should be same. Superclass(if any): extends keyword is used to establish parent-child relationship in java. Only one parent can be extended by a class (subclass). Modifiers : A class can have only public or default access modifier. Interfaces(if any): A class can have one or more interfaces as superclass. Keyword implements is used for same. Objects: It is a fundamental unit of object-oriented programming and reflects the entities of true life. A typical Java program generates a lot of objects that communicate with methods. An object is made up of: Identity : It provides an object a distinctive name and allows the interaction of one object with other objects. State : It is depicted by an object's properties. It also represents an object's characteristics. Behaviour: It is depicted by an object's methods. It also represents an object's reaction/response to other objects. Example of an object : cat Constructor A Constructor is a block of code that initializes a newly created object.  It is executed when an instance of the class is created. When constructor is called, memory for the object of class is allocated in heap It is a unique method in class which is used to initialize the object.At least one constructor is called each time an object is created using the new() keyword. Below are 3 rules for the constructor. A Constructor does not have return anything. The name of the constructor must be the same as the name of the class We cannot use Keywords like abstract, static, final and synchronized in constructor declaration. There are 3 types of constructors:  Default:  No-arg constructor: Parameterized: Default: Java compiler inserts a default constructor into your code on your behalf if you don't introduce any constructor in your class. This constructor is known as the default constructor. You wouldn't discover it in your source code (the java file) because it would be inserted into the code during compilation and remains in the file of.class. No-arg: The no-arg constructor is regarded as a constructor without arguments. The signature is the same as the default constructor, but unlike the default constructor, the body can have any code where the constructor body is empty. While you may see some people claim that the default and no-arg constructor is the same, in fact they aren't.Even if you write public MyClass() { } in your MyClass class, it can't be called the default constructor because you've written the code. class MyClass {    public MyClass()  {  System.out.println("This constructor is a no argument constructor");  }  public static void main(String args[]){  new MyClass();  }  } Parameterized: Constructor is known as Parameterized Constructor with arguments (or you can say parameters). In below example we have a parameterized constructor with two arguments; student id and student name. public class Student {  int stuId;    String stuName;    //parameterized constructor with two parameters Employee(int id, String name){    this.stuId = id;    this.stuName = name;       }    void info(){  System.out.println("Id: "+stuId+" Name: "+stuName);     }    public static void main(String args[]){    Student student1 = new Employee(1234,"Ashish");    Student student2 = new Employee(8765,"Rahul");    student1.info();    student2.info();       }    } Class Initialization Each class you declare can optionally provide a constructor with parameters that can be used to initialize an object of a class when the object is created. Java requires a constructor call for every object that's created, so this is the ideal point to initialize an object's instance variables. Example: Student student = new Student();  Student is object of class Student. Instant Initialization block Instance Initialization Block in Java: Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces. It is not at all necessary to include them in your classes. Example: classMyClassExample  {   // Instance Initialization Block   {   System.out.println("Instance block");   }   MyClassExample()   {   System.out.println("Constructor Called");   }   publicstaticvoidmain(String[] args)   {   MyClassExamplea = newMyClassExample();   }   }  Output : Instance block  Constructor Called Static keyword in java The static keyword is primarily used for memory management in java, and is used with variables, functions, blocks and class.This is used for a constant variable or a method which is the same for each class instance. Static block is used for initializing the static variables. This block gets executed when the class is loaded in the memory. A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program. Example: class StaticExample{  static int number;  static String mystring;  static{        number = 97;  mystring = "Static keyword in Java";     }  public static void main(String args[])     {  System.out.println("Value of number: "+number);  System.out.println("Value of mystring: "+mystring);     }  } Output: Value of number: 97 Value of mystring: Static keyword in Java This keyword Keyword is a reference variable in Java that refers to the current class object. This keyword is non static in nature. The different Java uses of this keyword are as follows: Can be passed as an parameter in the method call Can be used to refer to present class instance variable. Can be used to invoke current class constructor. Can be used to return the current class instance object Example:  class MyClassExample {  int instVar;  MyClassExample(int instVar){  this.instVar = instVar;  System.out.println("this reference = " + this);      }  public static void main(String[] args) {  MyClassExample obj = newMyClassExample(8);  System.out.println("object reference = " + obj);      }  } When you run the program, the output will be: this reference = com.ThisAndThat.MyClassExample@74a14482 object reference = com.ThisAndThat.MyClassExample@74a14482 Notice that the object id of obj and this is same. Meaning, this is nothing but the reference to the current object. Packages in Java Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used to prevent naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.pune.Employee and college.staff.delhi.Employee. For grouping associated classes, a package in Java is used. Think of it in a file directory as a folder. We use packages to prevent clashes with names and write a better code that can be maintained. Packages are divided into 2 categories: In built Packages (packages from the Java API) i.e. java.lang.* User-defined Packages (create your own packages/custom packages) Importing syntax: importpackage.name.Class; // Import a single class importpackage.name.*; // Import the whole package Built-in Packages: These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are: java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations. java.lang: Contains language support classes(e.g. classed which defines primitive data types, math operations). This package is automatically imported.java.io: Contains classed for supporting input / output operations.java.applet: Contains classes for creating Applets.java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).java.net: Contain classes for supporting networking operations. Object class in java By default, the Object class is the parent class of all Java classes. In other words, it is the highest java class. The object class in the java.lang package is present. Each Java class is obtained directly or indirectly from the class of the object. If a class does not extend any other class, it is an Object's immediate child class and if it expands another class, it is an indirect derivative. Therefore, all Java classes have access to the Object class methods.So Object class acts as a root of inheritance hierarchy in any Java application. The class of the object offer several methods. They're as follows: Object Class MethodMethod Descriptionpublic int hashCode()It returns the hashcode of object.public final Class getClass()It returns the Class class object of this object. The class can also be used to obtain this class ' metadata.public boolean equals(Object obj)It compares the 2 objects and returns true/false.public String toString()It returns a string representing the object.protected Object clone() throws CloneNotSupportedExceptionIt is used to create and return the clone of object.public final void wait(long timeout,int nanos)throws InterruptedExceptionIt causes the current thread to wait for the specified milliseconds and nanoseconds.public final void notify()It is used to wake up a single thread, which is waiting on this object's monitor.public final void notifyAll()It is used to wake up all the threads, which are waiting on this object's monitor.public final void wait(long timeout)throws InterruptedExceptionIt causes the current thread to wait for the specified milliseconds.protected void finalize()throws ThrowableIt is invoked by the garbage collector before an object is being garbage collected by JVM.public final void wait()throws InterruptedExceptionIt causes the current thread to wait, until another thread is notified (invoke notify()/notifyAll() method).Object Cloning in java Cloning the object is a way to generate an object's precise duplicate. Object class's clone() method is used to clone an object. The java.lang.Cloneable interface has to be implemented by the class we want to generate with the object clone. Clone() method produces CloneNotSupportedException if we do not implement Cloneable interface. Signature below: protected Object clone() throws CloneNotSupportedException The clone() method saves the task of extra processing to create the precise duplicate of an object. It will take a lot of processing timeif we use the new keyword to perform it, which is why we use cloning of objects. Advantage of Object cloning in java While Object.clone() has some problems with design, it is still a common and easy way to copy objects. Following is a list of clone() method benefits: Clone() is the fastest and simplest way to copy/clone an array. Using clone method it is easy to clone and we don't need to write long and repetitive codes.  Disadvantage of Object cloning in java Beloware the some disadvantages of clone() method: We need to alter a lot of syntaxes to our software to use the Object.clone() method, such as applying a Cloneable interface, defining the clone() method and managing CloneNotSupportedException, and lastly calling Object.clone() and so on. Object.clone() is protected, so we need to provide our own clone() and call Object.clone() from it indirectly. If you want to write a clone method in a child's class, all of its superclasses should write or inherit the clone() method from another parent class. Otherwise, it will fail the super.clone() chain. Object.clone() provide only shallow copying however if we need deep cloning we have to override clone method. class Worker implements Cloneable{  int id;  String name;  Worker(int id,String name){  this.id=id;  this.name=name;  }  public Object clone()throws CloneNotSupportedException{  return super.clone();  }  public static void main(String args[]){  try{  Workers1=new Worker(1011,"Ashish");  Workers2=(Worker)s1.clone();  System.out.println(s1.id+" "+s1.name);  System.out.println(s2.id+" "+s2.name);  }catch(CloneNotSupportedException c){}  }  } Output:1011 Ashish  1011 Ashish Instanceof operator The java operator's instanceof is used to check whether the object is a type of class or subclass or interface. Also known as the type comparison operator is the instanceof in java because it compares the instance to the type. It either returns true or false. If we apply the  operator instanceof with any null-value variable, it returns false. class Simple{   public static void main(String args[]){   Simple simple=new Simple();   System.out.println(simple instanceof Simple1);//true }
logo

Java Tutorial

Classes & Objects

Classes and objects are fundamental ideas of object-oriented programming that revolve around the entities of actual life. 

  • Object − Objects have behaviours and states. Example: A dog has states- colour, name, race and behaviour-wagging the tail, barking, eating. An object is a class instance.  
  • Class − A class can be described as a template / blueprint describing the behaviour / state supported by the object of its type. 

An object is a specimen of a class. Software objects are often used to model real-world objects you find in everyday life. 

A class is a blueprint or prototype defined by the user that creates objects from. It reflects the collection of characteristics or techniques prevalent to all single type objects. These elements that can generally be included in class declarations are listed below: 

  1. Body: The body of the class encircled by braces, { }. 
  2. Class name: The class name means name of class declared. Class name and file name should be same. 
  3. Superclass(if any): extends keyword is used to establish parent-child relationship in java. Only one parent can be extended by a class (subclass). 
  4. Modifiers : A class can have only public or default access modifier. 
  5. Interfaces(if any): A class can have one or more interfaces as superclass. Keyword implements is used for same. 
  6. Objects: It is a fundamental unit of object-oriented programming and reflects the entities of true life. A typical Java program generates a lot of objects that communicate with methods. An object is made up of: 
  7. Identity : It provides an object a distinctive name and allows the interaction of one object with other objects. 
  8. State : It is depicted by an object's properties. It also represents an object's characteristics. 
  9. Behaviour: It is depicted by an object's methods. It also represents an object's reaction/response to other objects. 

Example of an object : cat 

Constructor 

A Constructor is a block of code that initializes a newly created object.  It is executed when an instance of the class is created. When constructor is called, memory for the object of class is allocated in heap 

It is a unique method in class which is used to initialize the object.At least one constructor is called each time an object is created using the new() keyword. 

Below are 3 rules for the constructor. 

  1. A Constructor does not have return anything. 
  2. The name of the constructor must be the same as the name of the class 
  3. We cannot use Keywords like abstract, static, final and synchronized in constructor declaration. 

There are 3 types of constructors:  

  • Default:  
  • No-arg constructor: 
  • Parameterized: 

Default: Java compiler inserts a default constructor into your code on your behalf if you don't introduce any constructor in your class. This constructor is known as the default constructor. You wouldn't discover it in your source code (the java file) because it would be inserted into the code during compilation and remains in the file of.class. 

No-arg: The no-arg constructor is regarded as a constructor without arguments. The signature is the same as the default constructor, but unlike the default constructor, the body can have any code where the constructor body is empty. 

While you may see some people claim that the default and no-arg constructor is the same, in fact they aren't.Even if you write public MyClass() { } in your MyClass class, it can't be called the default constructor because you've written the code. 

class MyClass   public MyClass() 
{ 
   System.out.println("This constructor is a no argument constructor"); 
} 
public static void main(String args[]){ 
new MyClass(); 
} 
} 

Parameterized: Constructor is known as Parameterized Constructor with arguments (or you can say parameters). 

In below example we have a parameterized constructor with two arguments; student id and student name. 

public class Studentint stuId;   
String stuName;   
//parameterized constructor with two parameters 
Employee(int id, String name){   
this.stuId = id;   
this.stuName = name;   
   }   
void info(){ 
System.out.println("Id: "+stuId+" Name: "+stuName); 
   }   
public static void main(String args[]){   
Student student1 = new Employee(1234,"Ashish");   
Student student2 = new Employee(8765,"Rahul");   
student1.info();   
student2.info();   
   }   
} 

Class Initialization 

Each class you declare can optionally provide a constructor with parameters that can be used to initialize an object of a class when the object is created. Java requires a constructor call for every object that's created, so this is the ideal point to initialize an object's instance variables. 

Example: 

Student student = new Student(); 
Student is object of class Student. 

Instant Initialization block 

Instance Initialization Block in Java: 

  • Initialization blocks are executed whenever the class is initialized and before constructors are invoked. 
  • They are typically placed above the constructors within braces. 
  • It is not at all necessary to include them in your classes. 

Example: 

classMyClassExample 
{  
    // Instance Initialization Block  
    {   
System.out.println("Instance block");  
    }  
MyClassExample()  
    {  
System.out.println("Constructor Called");  
    }  
    publicstaticvoidmain(String[] args)  
    {  
MyClassExamplea = newMyClassExample();  
    }  
}  

Output : 

Instance block 
Constructor Called 

Static keyword in java 

The static keyword is primarily used for memory management in java, and is used with variables, functions, blocks and class.This is used for a constant variable or a method which is the same for each class instance. 

Static block is used for initializing the static variables. This block gets executed when the class is loaded in the memory. A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program. 

Example: 

class StaticExample{ 
static int number; 
static String mystring; 
static{ 
      number = 97; 
      mystring = "Static keyword in Java"; 
   } 
   public static void main(String args[]) 
   { 
System.out.println("Value of number: "+number); 
System.out.println("Value of mystring: "+mystring); 
   } 
} 

Output: 

Value of number: 97 
Value of mystring: Static keyword in Java 

This keyword 

Keyword is a reference variable in Java that refers to the current class object. This keyword is non static in nature. 

The different Java uses of this keyword are as follows: 

  • Can be passed as an parameter in the method call 
  • Can be used to refer to present class instance variable. 
  • Can be used to invoke current class constructor. 
  • Can be used to return the current class instance object 

Example:  

class MyClassExample int instVar; 
MyClassExample(int instVar){ 
this.instVar = instVar; 
System.out.println("this reference = " + this); 
    } 
public static void main(String[] args) { 
MyClassExample obj = newMyClassExample(8); 
System.out.println("object reference = " + obj); 
    } 
} 

When you run the program, the output will be: 

this reference = com.ThisAndThat.MyClassExample@74a14482 
object reference = com.ThisAndThat.MyClassExample@74a14482 

Notice that the object id of obj and this is same. Meaning, this is nothing but the reference to the current object. 

Packages in Java 

Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used to prevent naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.pune.Employee and college.staff.delhi.Employee. 

For grouping associated classes, a package in Java is used. Think of it in a file directory as a folder. We use packages to prevent clashes with names and write a better code that can be maintained. 

Packages are divided into 2 categories: 

  • In built Packages (packages from the Java API) i.e. java.lang.* 
  • User-defined Packages (create your own packages/custom packages) 

Importing syntax: 

importpackage.name.Class; // Import a single class 
importpackage.name.*; // Import the whole package 

Built-in Packages: 
These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are: 

  1. java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations. 
  2. java.lang: Contains language support classes(e.g. classed which defines primitive data types, math operations). This package is automatically imported.
  3. java.io: Contains classed for supporting input / output operations.
  4. java.applet: Contains classes for creating Applets.
  5. java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).
  6. java.net: Contain classes for supporting networking operations. 

Object class in java 

By default, the Object class is the parent class of all Java classes. In other words, it is the highest java class. 

The object class in the java.lang package is present. Each Java class is obtained directly or indirectly from the class of the object. If a class does not extend any other class, it is an Object's immediate child class and if it expands another class, it is an indirect derivative. Therefore, all Java classes have access to the Object class methods.So Object class acts as a root of inheritance hierarchy in any Java application. 

The class of the object offer several methods. They're as follows: 

Object Class MethodMethod Description
public int hashCode()It returns the hashcode of object.
public final Class getClass()It returns the Class class object of this object. The class can also be used to obtain this class ' metadata.
public boolean equals(Object obj)It compares the 2 objects and returns true/false.
public String toString()It returns a string representing the object.
protected Object clone() throws CloneNotSupportedExceptionIt is used to create and return the clone of object.
public final void wait(long timeout,int nanos)throws InterruptedExceptionIt causes the current thread to wait for the specified milliseconds and nanoseconds.
public final void notify()It is used to wake up a single thread, which is waiting on this object's monitor.
public final void notifyAll()It is used to wake up all the threads, which are waiting on this object's monitor.
public final void wait(long timeout)throws InterruptedExceptionIt causes the current thread to wait for the specified milliseconds.
protected void finalize()throws ThrowableIt is invoked by the garbage collector before an object is being garbage collected by JVM.
public final void wait()throws InterruptedExceptionIt causes the current thread to wait, until another thread is notified (invoke notify()/notifyAll() method).

Object Cloning in java 

Cloning the object is a way to generate an object's precise duplicate. Object class's clone() method is used to clone an object. The java.lang.Cloneable interface has to be implemented by the class we want to generate with the object clone. 

Clone() method produces CloneNotSupportedException if we do not implement Cloneable interface. Signature below: 

protected Object clone() throws CloneNotSupportedException 

The clone() method saves the task of extra processing to create the precise duplicate of an object. It will take a lot of processing timeif we use the new keyword to perform it, which is why we use cloning of objects. 

Advantage of Object cloning in java 

While Object.clone() has some problems with design, it is still a common and easy way to copy objects. Following is a list of clone() method benefits: 

  • Clone() is the fastest and simplest way to copy/clone an array. 
  • Using clone method it is easy to clone and we don't need to write long and repetitive codes.  

Disadvantage of Object cloning in java 

Beloware the some disadvantages of clone() method: 

  • We need to alter a lot of syntaxes to our software to use the Object.clone() method, such as applying a Cloneable interface, defining the clone() method and managing CloneNotSupportedException, and lastly calling Object.clone() and so on. 
  • Object.clone() is protected, so we need to provide our own clone() and call Object.clone() from it indirectly. 
  • If you want to write a clone method in a child's class, all of its superclasses should write or inherit the clone() method from another parent class. Otherwise, it will fail the super.clone() chain. 
  • Object.clone() provide only shallow copying however if we need deep cloning we have to override clone method. 
class Worker implements Cloneable{ 
int id; 
String name; 
Worker(int id,String name){ 
this.id=id; 
this.name=name; 
} 
public Object clone()throws CloneNotSupportedException{ 
return super.clone(); 
} 
public static void main(String args[]){ 
try{ 
Workers1=new Worker(1011,"Ashish"); 
Workers2=(Worker)s1.clone(); 
System.out.println(s1.id+" "+s1.name); 
System.out.println(s2.id+" "+s2.name); 
}catch(CloneNotSupportedException c){} 
} 
} 

Output:

1011 Ashish 
1011 Ashish 

Instanceof operator 

The java operator's instanceof is used to check whether the object is a type of class or subclass or interface. 

Also known as the type comparison operator is the instanceof in java because it compares the instance to the type. It either returns true or false. If we apply the  

operator instanceof with any null-value variable, it returns false. 

class Simple{   
public static voidmain(String args[]){   
 Simple simple=new Simple();   
System.out.println(simple instanceof Simple1);//true 
 }   

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

protective orders in virginia

Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.

Johnfrance

Thank you for your valuable information.

sam

Thank you for this wonderful article!

Belay Abera

This article was really helpful to me, thank you!

dfsdf

super article!