oops

ObjectOrientedProgramLanguage
  • The main aim of object-oriented programming is to implement real-world entities.
  • Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance.
Objects
  • Any entity that has state and behavior is known as an object.
  • An Object can be defined as an instance of a class. 
  • An object contains an address and takes up some space in memory.
  • Object is Dynamic memory allocation of class.
  • Object is an encapsulated in form of all Non-static methods&Non-static variables of a particular class .
  • The process "creating objects out of class" is known as instantiation.

Class

  • It user defined data type in java.
  • 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.
  • A class can also be defined as a blueprint that defines variables&methods  common to all objects.
  • Example↗:
                   public class student 
                     {
                      int usn;
                      string name;
                      string email;
                     void reading()
                       {
                           }
                     void writing()
                      {
                           }
                     void playing()
                      {
                           }
In above programs variables are usn,name,email.  Methods are reading,writing,playing.


1.Constructor

  • Constructor(s) of a class must has same name as the class name.
  • A constructor in Java can not be abstract, final, static and synchronized. Constructor has no return type. 
  •  Constructor is a block of code that initializes the newly created object.
  • constructor resembles an instance method in java but it's not a method as it doesn't have a return type

Types of Constructors

There are three types of constructors: Default, No-arg constructor and Parameterized.
types of constructor

Default constructor


  • Java compiler inserts a default constructor into your code on your behalf. This constructor is known as default constructor. 
default constructor
.

No-arg constructor:

Constructor with no arguments is known as no-arg constructor.
class Demo
{
     public Demo()
     {
         System.out.println("This is a no argument constructor");
     }
     public static void main(String args[]) {
      new Demo();
     }
}
Output:
This is a no argument constructor

Parameterized constructor

Constructor with arguments(or you can say parameters) is known as Parameterized constructor.
public class Employee {

   int empId;  
   String empName;  
     
   //parameterized constructor with two parameters
   Employee(int id, String name){  
       this.empId = id;  
       this.empName = name;  
   }  
   void info(){
        System.out.println("Id: "+empId+" Name: "+empName);
   }  
    
   public static void main(String args[]){  
 Employee obj1 = new Employee(10245,"Chaitanya");  
 Employee obj2 = new Employee(92232,"Negan");  
 obj1.info();  
 obj2.info();  
   }  
}
Output:
Id: 10245 Name: Chaitanya
Id: 92232 Name: Negan

Constructor Chaining

When A constructor calls another constructor of same class then this is called constructor chaining. Read more about it here. constructor chainingConstructor overloading in Java
  • 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.
Inheritance
  • Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.
  • Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).For Code Reusability.

Terms used in Inheritance

  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
  • Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

Types of inheritance in java

  1.  Single, 
  2. Multilevel and
  3.  Hierarchical.

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
  1. class Animal{  
  2. void eat(){System.out.println("eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void bark(){System.out.println("barking...");}  
  6. }  
  7. class TestInheritance{  
  8. public static void main(String args[]){  
  9. Dog d=new Dog();  
  10. d.bark();  
  11. d.eat();  
  12. }}  
Output:
barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
File: TestInheritance2.java
  1. class Animal{  
  2. void eat(){System.out.println("eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void bark(){System.out.println("barking...");}  
  6. }  
  7. class BabyDog extends Dog{  
  8. void weep(){System.out.println("weeping...");}  
  9. }  
  10. class TestInheritance2{  
  11. public static void main(String args[]){  
  12. BabyDog d=new BabyDog();  
  13. d.weep();  
  14. d.bark();  
  15. d.eat();  
  16. }}  
Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java
  1. class Animal{  
  2. void eat(){System.out.println("eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void bark(){System.out.println("barking...");}  
  6. }  
  7. class Cat extends Animal{  
  8. void meow(){System.out.println("meowing...");}  
  9. }  
  10. class TestInheritance3{  
  11. public static void main(String args[]){  
  12. Cat c=new Cat();  
  13. c.meow();  
  14. c.eat();  
  15. //c.bark();//C.T.Error  
  16. }}  
Output:
meowing...
eating...

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.
  1. class A{  
  2. void msg(){System.out.println("Hello");}  
  3. }  
  4. class B{  
  5. void msg(){System.out.println("Welcome");}  
  6. }  
  7. class C extends A,B{//suppose if it were  
  8.    
  9.  public static void main(String args[]){  
  10.    C obj=new C();  
  11.    obj.msg();//Now which msg() method would be invoked?  
  12. }  
  13. }  
Test it Now
 Compile Time Error

Encapsulation in Java

Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines.

encapsulation in java

We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.

It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.

Read-Only class

  1. //A Java class which has only getter methods.  
  2. public class Student{  
  3. //private data member  
  4. private String college="AKG";  
  5. //getter method for college  
  6. public String getCollege(){  
  7. return college;  
  8. }  
  9. }  

Now, you can't change the value of the college data member which is "AKG".

  1. s.setCollege("KITE");//will render compile time error  

Write-Only class

  1. //A Java class which has only setter methods.  
  2. public class Student{  
  3. //private data member  
  4. private String college;  
  5. //getter method for college  
  6. public void setCollege(String college){  
  7. this.college=college;  
  8. }  
  9. }