Saturday, July 27, 2019

Java OOPs Concepts

Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as a truly object-oriented programming language.
Smalltalk is considered the first truly object-oriented programming language.
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts:
  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented design:
  • Coupling
  • Cohesion
  • Association
  • Aggregation
  • Composition
Java OOPs Concepts

Object

Java Object Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.

Class

Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism in Java

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation in Java OOPs Concepts

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

Coupling

Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation.

Cohesion

Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces.

Association

Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects:
  • One to One
  • One to Many
  • Many to One, and
  • Many to Many
Let's understand the relationship with real-time examples. For example, One country can have one prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have one prime minister (many to one), and many ministers can have many departments (many to many).
Association can be undirectional or bidirectional.

Aggregation

Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects.

Composition

The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically.

Advantage of OOPs over Procedure-oriented programming language

1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented programming language, it is not easy to manage if code grows as project size increases.
2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global data can be accessed from anywhere.
Global Data Figure: Data Representation in Procedure-Oriented Programming

Object Data Figure: Data Representation in Object-Oriented Programming
3) OOPs provides the ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.


Java Naming conventions

Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc.
But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape.
All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code.

Advantage of naming conventions in java

By using standard Java naming conventions, you make your code easier to read for yourself and other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.
The following are the key rules that must be followed by every identifier:
  • The name must not contain any white spaces.
  • The name should not start with special characters like & (ampersand), $ (dollar), _ (underscore).
Let's see some other rules that should be followed by identifiers.

Class

  • It should start with the uppercase letter.
  • It should be a noun such as Color, Button, System, Thread, etc.
  • Use appropriate words, instead of acronyms.
  • Example: -
  1. public class Employee  
  2. {  
  3. //code snippet  
  4. }  

Interface

  • It should start with the uppercase letter.
  • It should be an adjective such as Runnable, Remote, ActionListener.
  • Use appropriate words, instead of acronyms.
  • Example: -
  1. interface Printable  
  2. {  
  3. //code snippet  
  4. }  

Method

  • It should start with lowercase letter.
  • It should be a verb such as main(), print(), println().
  • If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed().
  • Example:-
  1.  class Employee  
  2. {  
  3. //method  
  4. void draw()  
  5. {  
  6. //code snippet  
  7. }  
  8. }  

Variable

  • It should start with a lowercase letter such as id, name.
  • It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
  • If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as firstName, lastName.
  • Avoid using one-character variables such as x, y, z.
  • Example :-
  1.   class Employee  
  2. {  
  3. //variable  
  4. int id;  
  5. //code snippet  
  6. }  
Package
  • It should be a lowercase letter such as java, lang.
  • If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang.
  • Example :-
  1. package com.javatpoint; //package  
  2. class Employee  
  3. {  
  4. //code snippet  
  5. }  

Constant

  • It should be in uppercase letters such as RED, YELLOW.
  • If the name contains multiple words, it should be separated by an underscore(_) such as MAX_PRIORITY.
  • It may contain digits but not as the first letter.
  • Example :-
  1. class Employee  
  2. {  
  3. //constant  
  4.  static final int MIN_AGE = 18;  
  5. //code snippet  
  6. }  

CamelCase in java naming conventions

Java follows camel-case syntax for naming the class, interface, method, and variable.
If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.

What is an object in Java

object in Java An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
An object has three characteristics:
  • State: represents the data (value) of an object.
  • Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
  • Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
Characteristics of Object in Java For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.
Object Definitions:
  • An object is a real-world entity.
  • An object is a runtime entity.
  • The object is an entity which has state and behavior.
  • The object is an instance of a class.

What at is a class in Java?A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface
Class in Java

Syntax to declare a class:

  1. class <class_name>{  
  2.     field;  
  3.     method;  
  4. }  

Instance variable in Java

A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.

Method in Java

In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method

  • Code Reusability
  • Code Optimization

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.

Object and Class Example: main within the class

In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
File: Student.java
  1. //Java Program to illustrate how to define a class and fields  
  2. //Defining a Student class.  
  3. class Student{  
  4.  //defining fields  
  5.  int id;//field or data member or instance variable  
  6.  String name;  
  7.  //creating main method inside the Student class  
  8.  public static void main(String args[]){  
  9.   //Creating an object or instance  
  10.   Student s1=new Student();//creating an object of Student  
  11.   //Printing values of the object  
  12.   System.out.println(s1.id);//accessing member through reference variable  
  13.   System.out.println(s1.name);  
  14.  }  
  15. }  

Output:
0 
null

Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.
File: TestStudent1.java
  1. //Java Program to demonstrate having the main method in   
  2. //another class  
  3. //Creating Student class.  
  4. class Student{  
  5.  int id;  
  6.  String name;  
  7. }  
  8. //Creating another class TestStudent1 which contains the main method  
  9. class TestStudent1{  
  10.  public static void main(String args[]){  
  11.   Student s1=new Student();  
  12.   System.out.println(s1.id);  
  13.   System.out.println(s1.name);  
  14.  }  
  15. }  

Output:
0 
null

3 Ways to initialize object

There are 3 ways to initialize object in Java.
  1. By reference variable
  2. By method
  3. By constructor

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable.
File: TestStudent2.java
  1. class Student{  
  2.  int id;  
  3.  String name;  
  4. }  
  5. class TestStudent2{  
  6.  public static void main(String args[]){  
  7.   Student s1=new Student();  
  8.   s1.id=101;  
  9.   s1.name="Sonoo";  
  10.   System.out.println(s1.id+" "+s1.name);//printing members with a white space  
  11.  }  
  12. }  

Output:
101 Sonoo
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
  1. class Student{  
  2.  int id;  
  3.  String name;  
  4. }  
  5. class TestStudent3{  
  6.  public static void main(String args[]){  
  7.   //Creating objects  
  8.   Student s1=new Student();  
  9.   Student s2=new Student();  
  10.   //Initializing objects  
  11.   s1.id=101;  
  12.   s1.name="Sonoo";  
  13.   s2.id=102;  
  14.   s2.name="Amit";  
  15.   //Printing data  
  16.   System.out.println(s1.id+" "+s1.name);  
  17.   System.out.println(s2.id+" "+s2.name);  
  18.  }  
  19. }  
Output:
101 Sonoo
102 Amit

2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java
  1. class Student{  
  2.  int rollno;  
  3.  String name;  
  4.  void insertRecord(int r, String n){  
  5.   rollno=r;  
  6.   name=n;  
  7.  }  
  8.  void displayInformation(){System.out.println(rollno+" "+name);}  
  9. }  
  10. class TestStudent4{  
  11.  public static void main(String args[]){  
  12.   Student s1=new Student();  
  13.   Student s2=new Student();  
  14.   s1.insertRecord(111,"Karan");  
  15.   s2.insertRecord(222,"Aryan");  
  16.   s1.displayInformation();  
  17.   s2.displayInformation();  
  18.  }  
  19. }  

Output:
111 Karan
222 Aryan
Object in Java with values As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.

3) Object and Class Example: Initialization through a constructor

We will learn about constructors in Java later.

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.
File: TestEmployee.java
  1. class Employee{  
  2.     int id;  
  3.     String name;  
  4.     float salary;  
  5.     void insert(int i, String n, float s) {  
  6.         id=i;  
  7.         name=n;  
  8.         salary=s;  
  9.     }  
  10.     void display(){System.out.println(id+" "+name+" "+salary);}  
  11. }  
  12. public class TestEmployee {  
  13. public static void main(String[] args) {  
  14.     Employee e1=new Employee();  
  15.     Employee e2=new Employee();  
  16.     Employee e3=new Employee();  
  17.     e1.insert(101,"ajeet",45000);  
  18.     e2.insert(102,"irfan",25000);  
  19.     e3.insert(103,"nakul",55000);  
  20.     e1.display();  
  21.     e2.display();  
  22.     e3.display();  
  23. }  
  24. }  

Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
  1. class Rectangle{  
  2.  int length;  
  3.  int width;  
  4.  void insert(int l, int w){  
  5.   length=l;  
  6.   width=w;  
  7.  }  
  8.  void calculateArea(){System.out.println(length*width);}  
  9. }  
  10. class TestRectangle1{  
  11.  public static void main(String args[]){  
  12.   Rectangle r1=new Rectangle();  
  13.   Rectangle r2=new Rectangle();  
  14.   r1.insert(11,5);  
  15.   r2.insert(3,15);  
  16.   r1.calculateArea();  
  17.   r2.calculateArea();  
  18. }  
  19. }  

Output:
55 
45     

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:
  • By new keyword
  • By newInstance() method
  • By clone() method
  • By deserialization
  • By factory method etc.
We will learn these ways to create object later.
Different Ways to create an Object in Java

Anonymous object

Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only.
If you have to use an object only once, an anonymous object is a good approach. For example:
  1. new Calculation();//anonymous object  
Calling method through a reference:
  1. Calculation c=new Calculation();  
  2. c.fact(5);  
Calling method through an anonymous object
  1. new Calculation().fact(5);  
Let's see the full example of an anonymous object in Java.
  1. class Calculation{  
  2.  void fact(int  n){  
  3.   int fact=1;  
  4.   for(int i=1;i<=n;i++){  
  5.    fact=fact*i;  
  6.   }  
  7.  System.out.println("factorial is "+fact);  
  8. }  
  9. public static void main(String args[]){  
  10.  new Calculation().fact(5);//calling method with anonymous object  
  11. }  
  12. }  
Output:
Factorial is 120

Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.
Initialization of primitive variables:
  1. int a=10, b=20;  
Initialization of refernce variables:
  1. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects  
Let's see the example:
  1. //Java Program to illustrate the use of Rectangle class which  
  2. //has length and width data members  
  3. class Rectangle{  
  4.  int length;  
  5.  int width;  
  6.  void insert(int l,int w){  
  7.   length=l;  
  8.   width=w;  
  9.  }  
  10.  void calculateArea(){System.out.println(length*width);}  
  11. }  
  12. class TestRectangle2{  
  13.  public static void main(String args[]){  
  14.   Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  
  15.   r1.insert(11,5);  
  16.   r2.insert(3,15);  
  17.   r1.calculateArea();  
  18.   r2.calculateArea();  
  19. }  
  20. }  

Output:
55 
45     

Real World Example: Account

File: TestAccount.java
  1. //Java Program to demonstrate the working of a banking-system  
  2. //where we deposit and withdraw amount from our account.  
  3. //Creating an Account class which has deposit() and withdraw() methods  
  4. class Account{  
  5. int acc_no;  
  6. String name;  
  7. float amount;  
  8. //Method to initialize object  
  9. void insert(int a,String n,float amt){  
  10. acc_no=a;  
  11. name=n;  
  12. amount=amt;  
  13. }  
  14. //deposit method  
  15. void deposit(float amt){  
  16. amount=amount+amt;  
  17. System.out.println(amt+" deposited");  
  18. }  
  19. //withdraw method  
  20. void withdraw(float amt){  
  21. if(amount<amt){  
  22. System.out.println("Insufficient Balance");  
  23. }else{  
  24. amount=amount-amt;  
  25. System.out.println(amt+" withdrawn");  
  26. }  
  27. }  
  28. //method to check the balance of the account  
  29. void checkBalance(){System.out.println("Balance is: "+amount);}  
  30. //method to display the values of an object  
  31. void display(){System.out.println(acc_no+" "+name+" "+amount);}  
  32. }  
  33. //Creating a test class to deposit and withdraw amount  
  34. class TestAccount{  
  35. public static void main(String[] args){  
  36. Account a1=new Account();  
  37. a1.insert(832345,"Ankit",1000);  
  38. a1.display();  
  39. a1.checkBalance();  
  40. a1.deposit(40000);  
  41. a1.checkBalance();  
  42. a1.withdraw(15000);  
  43. a1.checkBalance();  
  44. }}   

Output:
832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Rules for creating Java constructor

There are two rules defined for the constructor.
  1. Constructor name must be the same as its class name
  2. A Constructor must have no explicit return type
  3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other words, we can have private, protected, public or default constructor in Java.

Types of Java constructors

There are two types of constructors in Java:
  1. Default constructor (no-arg constructor)
  2. Parameterized constructor
Java Constructors

Java Default Constructor 

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

  1. <class_name>(){}  

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
  1. //Java Program to create and call a default constructor  
  2. class Bike1{  
  3. //creating a default constructor  
  4. Bike1(){System.out.println("Bike is created");}  
  5. //main method  
  6. public static void main(String args[]){  
  7. //calling a default constructor  
  8. Bike1 b=new Bike1();  
  9. }  
  10. }  

Output:
Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Java default constructor

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.

Example of default constructor that displays the default values

  1. //Let us see another example of default constructor  
  2. //which displays the default values  
  3. class Student3{  
  4. int id;  
  5. String name;  
  6. //method to display the value of id and name  
  7. void display(){System.out.println(id+" "+name);}  
  8.   
  9. public static void main(String args[]){  
  10. //creating objects  
  11. Student3 s1=new Student3();  
  12. Student3 s2=new Student3();  
  13. //displaying values of the object  
  14. s1.display();  
  15. s2.display();  
  16. }  
  17. }  
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
  1. //Java Program to demonstrate the use of the parameterized constructor.  
  2. class Student4{  
  3.     int id;  
  4.     String name;  
  5.     //creating a parameterized constructor  
  6.     Student4(int i,String n){  
  7.     id = i;  
  8.     name = n;  
  9.     }  
  10.     //method to display the values  
  11.     void display(){System.out.println(id+" "+name);}  
  12.    
  13.     public static void main(String args[]){  
  14.     //creating objects and passing values  
  15.     Student4 s1 = new Student4(111,"Karan");  
  16.     Student4 s2 = new Student4(222,"Aryan");  
  17.     //calling method to display the values of object  
  18.     s1.display();  
  19.     s2.display();  
  20.    }  
  21. }  
Output:
111 Karan
222 Aryan

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading

  1. //Java program to overload constructors  
  2. class Student5{  
  3.     int id;  
  4.     String name;  
  5.     int age;  
  6.     //creating two arg constructor  
  7.     Student5(int i,String n){  
  8.     id = i;  
  9.     name = n;  
  10.     }  
  11.     //creating three arg constructor  
  12.     Student5(int i,String n,int a){  
  13.     id = i;  
  14.     name = n;  
  15.     age=a;  
  16.     }  
  17.     void display(){System.out.println(id+" "+name+" "+age);}  
  18.    
  19.     public static void main(String args[]){  
  20.     Student5 s1 = new Student5(111,"Karan");  
  21.     Student5 s2 = new Student5(222,"Aryan",25);  
  22.     s1.display();  
  23.     s2.display();  
  24.    }  
  25. }  
Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in Java

There are many differences between constructors and methods. They are given below.
Java ConstructorJava Method
A constructor is used to initialize the state of an object.A method is used to expose the behavior of an object.
A constructor must not have a return type.A method must have a return type.
The constructor is invoked implicitly.The method is invoked explicitly.
The Java compiler provides a default constructor if you don't have any constructor in a class.The method is not provided by the compiler in any case.
The constructor name must be same as the class name.The method name may or may not be same as the class name.

Java Constructors vs. Methods

Java Copy Constructor

There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java constructor.
  1. //Java program to initialize the values from one object to another object.  
  2. class Student6{  
  3.     int id;  
  4.     String name;  
  5.     //constructor to initialize integer and string  
  6.     Student6(int i,String n){  
  7.     id = i;  
  8.     name = n;  
  9.     }  
  10.     //constructor to initialize another object  
  11.     Student6(Student6 s){  
  12.     id = s.id;  
  13.     name =s.name;  
  14.     }  
  15.     void display(){System.out.println(id+" "+name);}  
  16.    
  17.     public static void main(String args[]){  
  18.     Student6 s1 = new Student6(111,"Karan");  
  19.     Student6 s2 = new Student6(s1);  
  20.     s1.display();  
  21.     s2.display();  
  22.    }  
  23. }  
Output:
111 Karan
111 Karan

Copying values without constructor

We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.
  1. class Student7{  
  2.     int id;  
  3.     String name;  
  4.     Student7(int i,String n){  
  5.     id = i;  
  6.     name = n;  
  7.     }  
  8.     Student7(){}  
  9.     void display(){System.out.println(id+" "+name);}  
  10.    
  11.     public static void main(String args[]){  
  12.     Student7 s1 = new Student7(111,"Karan");  
  13.     Student7 s2 = new Student7();  
  14.     s2.id=s1.id;  
  15.     s2.name=s1.name;  
  16.     s1.display();  
  17.     s2.display();  
  18.    }  
  19. }  

Output:
111 Karan
111 Karan

Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the constructor as you perform in the method.

Is there Constructor class in Java?

Yes.

What is the purpose of Constructor class?

Java provides a Constructor class which can be used to get the internal information of a constructor in the class. It is found in the java.lang.reflect package

The static keyword in Java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than an instance of the class.
The static can be:
  1. Variable (also known as a class variable)
  2. Method (also known as a class method)
  3. Block
  4. Nested class
Static in Java

1) Java static variable

If you declare any variable as static, it is known as a static variable.
  • The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.
  • The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable

  1. class Student{  
  2.      int rollno;  
  3.      String name;  
  4.      String college="ITS";  
  5. }  
Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to the common property of all objects. If we make it static, this field will get the memory only once.

Java static property is shared to all objects.

Example of static variable

  1. //Java Program to demonstrate the use of static variable  
  2. class Student{  
  3.    int rollno;//instance variable  
  4.    String name;  
  5.    static String college ="ITS";//static variable  
  6.    //constructor  
  7.    Student(int r, String n){  
  8.    rollno = r;  
  9.    name = n;  
  10.    }  
  11.    //method to display the values  
  12.    void display (){System.out.println(rollno+" "+name+" "+college);}  
  13. }  
  14. //Test class to show the values of objects  
  15. public class TestStaticVariable1{  
  16.  public static void main(String args[]){  
  17.  Student s1 = new Student(111,"Karan");  
  18.  Student s2 = new Student(222,"Aryan");  
  19.  //we can change the college of all objects by the single line of code  
  20.  //Student.college="BBDIT";  
  21.  s1.display();  
  22.  s2.display();  
  23.  }  
  24. }  
Output:
111 Karan ITS
222 Aryan ITS
Static Variable

Program of the counter without static variable

In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object will have the value 1 in the count variable.
  1. //Java Program to demonstrate the use of an instance variable  
  2. //which get memory each time when we create an object of the class.  
  3. class Counter{  
  4. int count=0;//will get memory each time when the instance is created  
  5.   
  6. Counter(){  
  7. count++;//incrementing value  
  8. System.out.println(count);  
  9. }  
  10.   
  11. public static void main(String args[]){  
  12. //Creating objects  
  13. Counter c1=new Counter();  
  14. Counter c2=new Counter();  
  15. Counter c3=new Counter();  
  16. }  
  17. }  

Output:
1
1
1

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
  1. //Java Program to illustrate the use of static variable which  
  2. //is shared with all objects.  
  3. class Counter2{  
  4. static int count=0;//will get memory only once and retain its value  
  5.   
  6. Counter2(){  
  7. count++;//incrementing the value of static variable  
  8. System.out.println(count);  
  9. }  
  10.   
  11. public static void main(String args[]){  
  12. //creating objects  
  13. Counter2 c1=new Counter2();  
  14. Counter2 c2=new Counter2();  
  15. Counter2 c3=new Counter2();  
  16. }  
  17. }  

Output:
1
2
3

2) Java static method

If you apply static keyword with any method, it is known as static method.
  • A static method belongs to the class rather than the object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • A static method can access static data member and can change the value of it.

Example of static method

  1. //Java Program to demonstrate the use of a static method.  
  2. class Student{  
  3.      int rollno;  
  4.      String name;  
  5.      static String college = "ITS";  
  6.      //static method to change the value of static variable  
  7.      static void change(){  
  8.      college = "BBDIT";  
  9.      }  
  10.      //constructor to initialize the variable  
  11.      Student(int r, String n){  
  12.      rollno = r;  
  13.      name = n;  
  14.      }  
  15.      //method to display values  
  16.      void display(){System.out.println(rollno+" "+name+" "+college);}  
  17. }  
  18. //Test class to create and display the values of object  
  19. public class TestStaticMethod{  
  20.     public static void main(String args[]){  
  21.     Student.change();//calling change method  
  22.     //creating objects  
  23.     Student s1 = new Student(111,"Karan");  
  24.     Student s2 = new Student(222,"Aryan");  
  25.     Student s3 = new Student(333,"Sonoo");  
  26.     //calling display method  
  27.     s1.display();  
  28.     s2.display();  
  29.     s3.display();  
  30.     }  
  31. }  

Output:111 Karan BBDIT
       222 Aryan BBDIT
       333 Sonoo BBDIT

Another example of a static method that performs a normal calculation

  1. //Java Program to get the cube of a given number using the static method  
  2.   
  3. class Calculate{  
  4.   static int cube(int x){  
  5.   return x*x*x;  
  6.   }  
  7.   
  8.   public static void main(String args[]){  
  9.   int result=Calculate.cube(5);  
  10.   System.out.println(result);  
  11.   }  
  12. }  

Output:125

Restrictions for the static method

There are two main restrictions for the static method. They are:
  1. The static method can not use non static data member or call non-static method directly.
  2. this and super cannot be used in static context.
  1. class A{  
  2.  int a=40;//non static  
  3.    
  4.  public static void main(String args[]){  
  5.   System.out.println(a);  
  6.  }  
  7. }        

Output:Compile Time Error

Q) Why is the Java main method static?

Ans) It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.

3) Java static block

  • Is used to initialize the static data member.
  • It is executed before the main method at the time of classloading.

Example of static block

  1. class A2{  
  2.   static{System.out.println("static block is invoked");}  
  3.   public static void main(String args[]){  
  4.    System.out.println("Hello main");  
  5.   }  
  6. }  

Output:static block is invoked
       Hello main

Q) Can we execute a program without main() method?

Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a java class without the main method.
  1. class A3{  
  2.   static{  
  3.   System.out.println("static block is invoked");  
  4.   System.exit(0);  
  5.   }  
  6. }  

Output:
static block is invoked
Since JDK 1.7 and above, output would be:
Error: Main method not found in class A3, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

No comments:

Post a Comment