Classes and objects are fundamental ideas of object-oriented programming that revolve around the entities of actual life.
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:
Example of an object : cat
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.
There are 3 types of constructors:
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(); } }
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.
Instance Initialization Block in Java:
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
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
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:
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.
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:
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:
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 Method | Method 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 CloneNotSupportedException | It is used to create and return the clone of object. |
public final void wait(long timeout,int nanos)throws InterruptedException | It 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 InterruptedException | It causes the current thread to wait for the specified milliseconds. |
protected void finalize()throws Throwable | It is invoked by the garbage collector before an object is being garbage collected by JVM. |
public final void wait()throws InterruptedException | It causes the current thread to wait, until another thread is notified (invoke notify()/notifyAll() method). |
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:
Disadvantage of Object cloning in java
Beloware the some disadvantages of 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
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 }
Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.
Thank you for your valuable information.
Thank you for this wonderful article!
This article was really helpful to me, thank you!
super article!
Leave a Reply
Your email address will not be published. Required fields are marked *