Java OOP

By ukmodak | March 31st 2024 10:34:01 AM | viewed 642 times

What is Class?

A Class is a blue print or Concept or idea of an Object

Class is a prototype of an object that models the attributes and methods of an object

Class can not be used directly; at first, an object is to be created. The process of creating object is known as instantiation or object creation.

What are Object?

Object is an instance of a Class

Every object contains some properties and methods

Properties are attributes that an object holds and methods are the actions or operations those can be performed on those attributes of that object.

If the value of an attribute is changed, according to OOP it is said that the State of an object is changed. Generally, the methods are responsible to change those object states.

The Principal of OOP/ Characteristics of OOP:

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

Abstraction

  • Combining the related attributes and methods into one class is known as abstraction
  • The objective of the abstraction is to hide the attributes and methods from other class
  • Creating Class is the example of Abstraction

Encapsulation

  • Accessing the attributes through the methods is known as encapsulation.
  • The objective of the encapsulation is to protect the attributes of a class from direct access.
  • Declaring methods to use attributes is the example of Encapsulation

Inheritance

  • Inheritance is a mechanism to create a class from an existing class
  • The existing class is known as Parent / Base / Super class
  • The new class is known as Child / Derived / Sub class.
  • According to inheritance, the Child class gets all the members (attributes and methods are collectively known as members) of the Parent class.
  • In fact, the child class has the members of it’s parent class and it’s own members.
  • Polymorphism

  • The term polymorphism means “One name many behaviors”.
  • In OOP, if we declare more than one methods with same name but with different signature (method name and parameter list collectively known as method Signature), then it is said that polymorphism is done.
  • Apart from these concepts, there are some other terms which are used in Object-Oriented design:

    • Coupling
    • Cohesion
    • Association
    • Aggregation
    • Composition

    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.

    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.

    Constructor in Java

    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 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
        //Java Program to create and call a default constructor  
        class Bike1{  
        //creating a default constructor  
        Bike1(){System.out.println("Bike is created");}  
        //main method  
        public static void main(String args[]){  
        //calling a default constructor  
        Bike1 b=new Bike1();  
        }  
        } 
    
    Output:
    
    Bike is created
    	
    
    Example of default constructor that displays the default values
           //Let us see another example of default constructor  
        //which displays the default values  
        class Student3{  
        int id;  
        String name;  
        //method to display the value of id and name  
        void display(){System.out.println(id+" "+name);}  
          
        public static void main(String args[]){  
        //creating objects  
        Student3 s1=new Student3();  
        Student3 s2=new Student3();  
        //displaying values of the object  
        s1.display();  
        s2.display();  
        }  
        }  
    	
    	Output:
    
    0 null
    0 null
    
    

    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.

          //Java Program to demonstrate the use of the parameterized constructor.  
        class Student4{  
            int id;  
            String name;  
            //creating a parameterized constructor  
            Student4(int i,String n){  
            id = i;  
            name = n;  
            }  
            //method to display the values  
            void display(){System.out.println(id+" "+name);}  
           
            public static void main(String args[]){  
            //creating objects and passing values  
            Student4 s1 = new Student4(111,"Karan");  
            Student4 s2 = new Student4(222,"Aryan");  
            //calling method to display the values of object  
            s1.display();  
            s2.display();  
           }  
        }  
    	
    	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
             //Java program to overload constructors  
        class Student5{  
            int id;  
            String name;  
            int age;  
            //creating two arg constructor  
            Student5(int i,String n){  
            id = i;  
            name = n;  
            }  
            //creating three arg constructor  
            Student5(int i,String n,int a){  
            id = i;  
            name = n;  
            age=a;  
            }  
            void display(){System.out.println(id+" "+name+" "+age);}  
           
            public static void main(String args[]){  
            Student5 s1 = new Student5(111,"Karan");  
            Student5 s2 = new Student5(222,"Aryan",25);  
            s1.display();  
            s2.display();  
           }  
        }  
    
    Test it Now
    
    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 Constructor Java 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 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.

        //Java program to initialize the values from one object to another object.  
        class Student6{  
            int id;  
            String name;  
            //constructor to initialize integer and string  
            Student6(int i,String n){  
            id = i;  
            name = n;  
            }  
            //constructor to initialize another object  
            Student6(Student6 s){  
            id = s.id;  
            name =s.name;  
            }  
            void display(){System.out.println(id+" "+name);}  
           
            public static void main(String args[]){  
            Student6 s1 = new Student6(111,"Karan");  
            Student6 s2 = new Student6(s1);  
            s1.display();  
            s2.display();  
           }  
        }  
    
    Test it Now
    
    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.

            class Student7{  
            int id;  
            String name;  
            Student7(int i,String n){  
            id = i;  
            name = n;  
            }  
            Student7(){}  
            void display(){System.out.println(id+" "+name);}  
           
            public static void main(String args[]){  
            Student7 s1 = new Student7(111,"Karan");  
            Student7 s2 = new Student7();  
            s2.id=s1.id;  
            s2.name=s1.name;  
            s1.display();  
            s2.display();  
           }  
        } 
    
    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.

    Java static keyword

    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

    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.

    Example of static variable
        //Java Program to demonstrate the use of static variable  
        class Student{  
           int rollno;//instance variable  
           String name;  
           static String college ="ITS";//static variable  
           //constructor  
           Student(int r, String n){  
           rollno = r;  
           name = n;  
           }  
           //method to display the values  
           void display (){System.out.println(rollno+" "+name+" "+college);}  
        }  
        //Test class to show the values of objects  
        public class TestStaticVariable1{  
         public static void main(String args[]){  
         Student s1 = new Student(111,"Karan");  
         Student s2 = new Student(222,"Aryan");  
         //we can change the college of all objects by the single line of code  
         //Student.college="BBDIT";  
         s1.display();  
         s2.display();  
         }  
        }  
    
    Test it Now
    
    Output:
    
    111 Karan ITS
    222 Aryan ITS
    
    
    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.

            //Java Program to demonstrate the use of an instance variable  
        //which get memory each time when we create an object of the class.  
        class Counter{  
        int count=0;//will get memory each time when the instance is created  
          
        Counter(){  
        count++;//incrementing value  
        System.out.println(count);  
        }  
          
        public static void main(String args[]){  
        //Creating objects  
        Counter c1=new Counter();  
        Counter c2=new Counter();  
        Counter c3=new Counter();  
        }  
        }  
    
    Test it Now
    
    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.

                //Java Program to illustrate the use of static variable which  
        //is shared with all objects.  
        class Counter2{  
        static int count=0;//will get memory only once and retain its value  
          
        Counter2(){  
        count++;//incrementing the value of static variable  
        System.out.println(count);  
        }  
          
        public static void main(String args[]){  
        //creating objects  
        Counter2 c1=new Counter2();  
        Counter2 c2=new Counter2();  
        Counter2 c3=new Counter2();  
        }  
        }  
    
    Test it Now
    
    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
      
        //Java Program to demonstrate the use of a static method.  
        class Student{  
             int rollno;  
             String name;  
             static String college = "ITS";  
             //static method to change the value of static variable  
             static void change(){  
             college = "BBDIT";  
             }  
             //constructor to initialize the variable  
             Student(int r, String n){  
             rollno = r;  
             name = n;  
             }  
             //method to display values  
             void display(){System.out.println(rollno+" "+name+" "+college);}  
        }  
        //Test class to create and display the values of object  
        public class TestStaticMethod{  
            public static void main(String args[]){  
            Student.change();//calling change method  
            //creating objects  
            Student s1 = new Student(111,"Karan");  
            Student s2 = new Student(222,"Aryan");  
            Student s3 = new Student(333,"Sonoo");  
            //calling display method  
            s1.display();  
            s2.display();  
            s3.display();  
            }  
        }  
    
    Test it Now
    
    Output:111 Karan BBDIT
           222 Aryan BBDIT
           333 Sonoo BBDIT
    
    
    Another example of a static method that performs a normal calculation
      
           //Java Program to get the cube of a given number using the static method  
          
        class Calculate{  
          static int cube(int x){  
          return x*x*x;  
          }  
          
          public static void main(String args[]){  
          int result=Calculate.cube(5);  
          System.out.println(result);  
          }  
        }  
    
    Test it Now
    
    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.
      
        class A{  
         int a=40;//non static  
           
         public static void main(String args[]){  
          System.out.println(a);  
         }  
        }        
    
    Test it Now
    
    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
      
        class A2{  
          static{System.out.println("static block is invoked");}  
          public static void main(String args[]){  
           System.out.println("Hello main");  
          }  
        }  
    
    Test it Now
    
    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.

        class A3{  
          static{  
          System.out.println("static block is invoked");  
          System.exit(0);  
          }  
        }  
    
    Test it Now
    Output:
    static block is invoked
    
    

    this keyword in java

    There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.

    Usage of java this keyword

    Here is given the 6 usage of java this keyword.

    1. this can be used to refer current class instance variable.
    2. this can be used to invoke current class method (implicitly)
    3. this() can be used to invoke current class constructor.
    4. this can be passed as an argument in the method call.
    5. this can be passed as argument in the constructor call.
    6. this can be used to return the current class instance from the method.

    Suggestion: If you are beginner to java, lookup only three usage of this keyword

    1) this: to refer current class instance variable The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.

    Understanding the problem without this keyword

    Let's understand the problem if we don't use this keyword by the example given below:

        class Student{  
        int rollno;  
        String name;  
        float fee;  
        Student(int rollno,String name,float fee){  
        rollno=rollno;  
        name=name;  
        fee=fee;  
        }  
        void display(){System.out.println(rollno+" "+name+" "+fee);}  
        }  
        class TestThis1{  
        public static void main(String args[]){  
        Student s1=new Student(111,"ankit",5000f);  
        Student s2=new Student(112,"sumit",6000f);  
        s1.display();  
        s2.display();  
        }}  
    
    Test it Now
    
    Output:
    
    0 null 0.0
    0 null 0.0
    
    

    In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.

    Solution of the above problem by this keyword
        class Student{  
        int rollno;  
        String name;  
        float fee;  
        Student(int rollno,String name,float fee){  
        this.rollno=rollno;  
        this.name=name;  
        this.fee=fee;  
        }  
        void display(){System.out.println(rollno+" "+name+" "+fee);}  
        }  
          
        class TestThis2{  
        public static void main(String args[]){  
        Student s1=new Student(111,"ankit",5000f);  
        Student s2=new Student(112,"sumit",6000f);  
        s1.display();  
        s2.display();  
        }}  
    
    Test it Now
    
    Output:
    
    111 ankit 5000
    112 sumit 6000
    
    

    If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:

    Program where this keyword is not required
        class Student{  
        int rollno;  
        String name;  
        float fee;  
        Student(int r,String n,float f){  
        rollno=r;  
        name=n;  
        fee=f;  
        }  
        void display(){System.out.println(rollno+" "+name+" "+fee);}  
        }  
          
        class TestThis3{  
        public static void main(String args[]){  
        Student s1=new Student(111,"ankit",5000f);  
        Student s2=new Student(112,"sumit",6000f);  
        s1.display();  
        s2.display();  
        }}  
    
    Test it Now
    
    Output:
    
    111 ankit 5000
    112 sumit 6000
    
    

    2) this: to invoke current class method

    You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example

        class A{  
        void m(){System.out.println("hello m");}  
        void n(){  
        System.out.println("hello n");  
        //m();//same as this.m()  
        this.m();  
        }  
        }  
        class TestThis4{  
        public static void main(String args[]){  
        A a=new A();  
        a.n();  
        }}  
    
    Test it Now
    
    Output:
    
    hello n
    hello m
    
    

    3) this() : to invoke current class constructor

    The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.

    Calling default constructor from parameterized constructor:

        class A{  
        A(){System.out.println("hello a");}  
        A(int x){  
        this();  
        System.out.println(x);  
        }  
        }  
        class TestThis5{  
        public static void main(String args[]){  
        A a=new A(10);  
        }}  
    
    Test it Now
    
    Output:
    
    hello a
    10
    
    

    Calling parameterized constructor from default constructor:

        class A{  
        A(){  
        this(5);  
        System.out.println("hello a");  
        }  
        A(int x){  
        System.out.println(x);  
        }  
        }  
        class TestThis6{  
        public static void main(String args[]){  
        A a=new A();  
        }}  
    
    Test it Now
    
    Output:
    
    5
    hello a
    
    

    Real usage of this() constructor call

    The this() constructor call should be used to reuse the constructor from the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword.

        class Student{  
        int rollno;  
        String name,course;  
        float fee;  
        Student(int rollno,String name,String course){  
        this.rollno=rollno;  
        this.name=name;  
        this.course=course;  
        }  
        Student(int rollno,String name,String course,float fee){  
        this(rollno,name,course);//reusing constructor  
        this.fee=fee;  
        }  
        void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}  
        }  
        class TestThis7{  
        public static void main(String args[]){  
        Student s1=new Student(111,"ankit","java");  
        Student s2=new Student(112,"sumit","java",6000f);  
        s1.display();  
        s2.display();  
        }} 
    
    Output:
    
    111 ankit java null
    112 sumit java 6000
    
    
    
        class Student{  
        int rollno;  
        String name,course;  
        float fee;  
        Student(int rollno,String name,String course){  
        this.rollno=rollno;  
        this.name=name;  
        this.course=course;  
        }  
        Student(int rollno,String name,String course,float fee){  
        this.fee=fee;  
        this(rollno,name,course);//C.T.Error  
        }  
        void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}  
        }  
        class TestThis8{  
        public static void main(String args[]){  
        Student s1=new Student(111,"ankit","java");  
        Student s2=new Student(112,"sumit","java",6000f);  
        s1.display();  
        s2.display();  
        }}  
    
    Test it Now
    
    Compile Time Error: Call to this must be first statement in constructor
    
    	
    

    4) this: to pass as an argument in the method

    The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example:

        class S2{  
          void m(S2 obj){  
          System.out.println("method is invoked");  
          }  
          void p(){  
          m(this);  
          }  
          public static void main(String args[]){  
          S2 s1 = new S2();  
          s1.p();  
          }  
        }  
    
    Test it Now
    
    Output:
    
    method is invoked
    
    

    Application of this that can be passed as an argument:

    In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to reuse one object in many methods.

    5) this: to pass as argument in the constructor call

    We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example:

        class B{  
          A4 obj;  
          B(A4 obj){  
            this.obj=obj;  
          }  
          void display(){  
            System.out.println(obj.data);//using data member of A4 class  
          }  
        }  
          
        class A4{  
          int data=10;  
          A4(){  
           B b=new B(this);  
           b.display();  
          }  
          public static void main(String args[]){  
           A4 a=new A4();  
          }  
        }  
    
    Test it Now
    
    Output:10
    
    

    6) this keyword can be used to return current class instance

    We can return this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example:

    Syntax of this that can be returned as a statement

    
        return_type method_name(){  
        return this;  
        }  
    

    Example of this keyword that you return as a statement from the method

        class A{  
        A getA(){  
        return this;  
        }  
        void msg(){System.out.println("Hello java");}  
        }  
        class Test1{  
        public static void main(String args[]){  
        new A().getA().msg();  
        }  
        }  
    	
    	Output:
    
    Hello java
    
    

    Proving this keyword

    Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same.
    
        class A5{  
        void m(){  
        System.out.println(this);//prints same reference ID  
        }  
        public static void main(String args[]){  
        A5 obj=new A5();  
        System.out.println(obj);//prints the reference ID  
        obj.m();  
        }  
        }  
    
    Test it Now
    
    Output:
    
    A5@22b3ea59
    A5@22b3ea59
    
    
    bONEandALL
    Visitor

    Total : 20972

    Today :26

    Today Visit Country :

    • Germany
    • United States
    • Singapore
    • China
    • United Kingdom
    • South Korea
    • Czechia