O O P S - Java

Basic


  • Programming Technique
    • Procedural Programming
      • Top-to-Bottom approach => Functions
    • Object-oriented Programming
      • Classes, Objects
      • 4 pillars => Inheritance, Polymorphism, Encapsulation, Abstraction
  • Static
    • Common for all Objects of that Class, Belongs to Class instead of Object
    • static dataType var = val; => Initialize a static variable
    • Class.var => Called using Class instead of Object
    • Can be accessed without creating a Object
    • Static method can only change value of Static data member
    • this & super can't be used in Static method

Class


  • Class is Group of Items (Clustering, Generalization), User-defined data type
  • It is a blueprint => Design/Type
    • State/Property/Field/Data Member/Attributes
    • Behavior/Function/Data Function/Methods
  • Syntax
    • Creating a Class
        public class ClassName {}
      
    • Class created by default
        public class Main {}
      
    • ClassName.var => To access a static variable no need to create a Object

Object


  • Implementation/Instance of class (Specialization)
    • Entity that contains its State & Behavior
  • Object is something that occupies space (memory) => Takes memory in Heap
  • If the Object is not initialized while declaration then it will give an exception in case of Primitive data type
  • Initialization with "new" keyword gives a "null" value by default
  • this => It represents current Object
    • Used to access Methods and Parameters of the Object
  • Syntax
    • Creating a Object from a Class
        ClassName var = new ClassName();
      
    • Creating a Object that can be used only once
        new ClassName();
      
    • Calling a Function from a Object of a Class
        var.functionName(arguments);
      
    • Using Wrapper Class to create Objects of primitive data types => Behind the scene new keyword is being used, Stored in Stack during Compile time, Access the methods using .
        Integer var = val;
        Integer var = null;
        Double var = val;
      
    • var = null => De-allocation of Memory in java GC, Pointer will point to nothing, Does not means 0

Constructor


  • Used for initialization
  • Gets called on Object creation
    • Have same name as Class name and does not have a return data type
    • Can't use abstract/static/final/synchronized with Constructor
  • If there are no Constructor then system will automatically define variables with default value
  • Constructor can also be private => To control how the class is instantiated
  • Constructor Chaining
    • this(arguments); => Calls another Constructor
    • This should be the first line in Constructor while calling another Constructor
  • Constructor Overloading
    • Having same name but different parameters, Can be applied with parameterized constructors
  • Types
    • Default/No Argument

      • Creating
          public ClassName () {
            var = val;
          }
        
      • Calling it
          ClassName var = new ClassName();
        
    • Parameterized

      • Creating this Constructor without Default Constructor will give error while Declaring an Object without passing arguments
      • Creating a parametrized Constructor
          ClassName (dataType val) {
            // "this" keyword is used to access the Property of current Object
            this.var = val;
          }
        
      • Calling it
          ClassName var = new ClassName(val);
        
    • Copy

      • Shallow copy => Any changes made in referenced objects in object X or Y will be reflected in other objects

      • Deep Copy => A deep copy copies all fields and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers

      • Creating a Copy Constructor

          ClassName (ClassName var) {
            this.var1 = var.var1;
          }
        
      • Calling it

          ClassName var = new ClassName(objectName);
        
      • Object Cloning => Can be used instead of Copy Constructor

          class ClassName implements Cloneable {
            int var;
        
            ClassName(int var) {
              this.var = var;
            }
        
            // For shallow copy
            public Object clone() throws CloneNotSupportedException {
              // To obtain the cloned object reference
              return super.clone();
            }
        
            public static void main(String args[]) {
              try {
                ClassName c1 = new ClassName(val);
                ClassName c2 = (ClassName)c1.clone();
              } catch(CloneNotSupportedException c) {}
            }
          }
        
    • Destructor

      • finalize()

Inheritance


  • Allows reusability
  • extends => This keyword is used
  • Types
    • Single
      • B extends A
      • Creating
          public class ClassName1 extends ClassName {
            // Statements
          }
        
      • super => Used to access methods of Parent/Base class from children class
    • Multi-level
      • B extends A & C extends B
      • Creating
          public class ClassName1 extends ClassName {
            // Statements
          }
          public class ClassName2 extends ClassName1 {
            // Statements
          }
        
    • Hierarchical
      • B, C extends A
      • Creating
          public class ClassName1 extends ClassName {
            // Statements
          }
          public class ClassName2 extends ClassName {
            // Statements
          }
        
    • Multiple
      • Not valid to prevent ambiguity, Can inherit multiple Interfaces
      • C extends A, B => A & B should be Interfaces
    • Hybrid/Multi-path
      • Diamond Problem => B, C extends A & D extends B, C => B & C should be interfaces and not Class
  • Object Creation
    • To access all the members present in both parent and child classes, as we are inheriting the properties
        ChildClass c = new ChildClass();
      
    • To access only the members present in the parent class and the methods which are overridden in the child class. This is because the parent class is upcasted to the child class
        ParentClass c = new ChildClass();
      

Polymorphism


  • Same Objects acting in many forms => Depending on Overloaded/Overridden methods
  • ClassName var = new ClassName1(); => Making Object from children Class, At compile time it acts as an Object of parent Class and at run time it acts as an Object of child Class
  • Types
    • Compile-time Polymorphism => Function/Method Overloading
      • Same function with different functionalities based on Parameters
      • In java this can also be done by changing the returnType
      • We can overload the main method in java but JVM only calls the original main method, it will never call our overloaded main method
      • ClassName.main(arguments); => To call a overloaded main method from default main method
    • Run-time Polymorphism => Function/Method Overriding
      • Same function with different functionalities in different Classes
      • Name & parameter should be same of functions, Works only with Inheritance
      • @Override => Mentioned before writing Overridden method, Optional to write
      • We cannot override main method of java because a static method cannot be overridden
      • We cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time

Encapsulation


  • Group of related data into a single pack => Wrapping up data member and function into a single Class/Unit
  • Fully encapsulated class => ALl data members are private
  • Getters => Used to get a private variable
    • Creating a Getter Function
        public returnType getVarName () {
          return var;
        }
      
  • Setters => Used to set a private variable
    • Creating a Setter Function
        public void setVarName (dataType val) {
          this.var = val;
        }
      
  • Access Modifiers => Used for Data Hiding for Properties or Methods
    • default
      • Accessible within the same Package/Directory
      • dataType var = val;
    • private
      • Accessible only within the Class
      • private dataType var = val;
    • public
      • Accessible to everyone
      • public dataType var = val;
      • Can only create one public class in a file or else gives compile-time error => Class name should be same a s file name
    • protected
      • Accessible to everyone but only through child class
      • protected dataType var = val;

Abstraction


  • Showing only essential details
  • Reduces complexity of viewing things
  • Can be achieved by
    • Abstract class
      • abstract keyword is used
          abstract class ClassName {}
        
      • Declared without implementation
      • May or may not have all abstract methods => Have come concrete methods
      • No object of abstract class possible
      • Abstract class can have constructor
      • Pure Abstraction => All methods are without implementation
    • Interfaces
Share: