0% found this document useful (0 votes)
13 views72 pages

Season 2

Uploaded by

Dauntless
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views72 pages

Season 2

Uploaded by

Dauntless
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Season 2 - OOPS

Object Oriented Programming Structure

It helps to design an object better and seems very close to the real world
Examples: studentName, RollNo, Gender(non static variables)
Study, read, write (non-static methods)
There are four basic pillars of OOPs:
1) Encapsulation
2) Inheritance
3) Polymorphism
4) Abstraction

Encapsulation
The process of binding or wrapping the states and behavior of an object in single unit is
known as Encapsulation.
State refers to non static variable and behavior refers to non static method.
Encapsulation can be achieved with the help of class.
The advantage of encapsulation is Data hiding.

Data hiding

It is the process of restricting direct access to the data member by providing indirect
secure access via methods.
With data hiding we can provide security for our data members.
The advantage of data hiding is verification and validation.

Steps to achieve data hiding

Step 1 - Prefix the data member with private keyword / Access modifier.
Example - private int age;

Step 2 - Use getter and setter methods to access the data member of another class.

Getter method is used to get the data or fetch the data.


The return type of getter method should be same as the data type of our private member.
Setter method is used to set the data or modify the data.
The return type of setter method is void.
Private

In Java we can achieve data hiding by using private keyword.


Private is a keyword and it is Access modifier.
If we prefix data member as private, within the same class we can access the private data
member directly. But Direct Access for accessing the data member outside the class is
restricted.
If we want to access the private data member from another class we need to create a
getter and setter method.

Note

If you want to get the data then create only getter() method.
If you want to modify the data then only create the setter() method.
If you want to get the data as well as modify the data then create both getter() and
setter() method.
If you don't want to get the data or as well as modify the data then don't create any
getter() and setter() method.
Inheritance
Inheritance comes under IS-A relationship.
The relationship which is similar to parent and child is known as IS-A relationship
In IS-A relationship, all the properties of parent class will get inherited in the child class.
In Java we can achieve inheritance with the help of extends keyword and implements
keyword.
Using inheritance we can achieve generalization and specialization.
Parent class is known as generalized class and Child class is known as specialized class.
All the properties will get inherited from parent to child class except constructor, private
data members and multiline initializers.

In inheritance the properties of parent get inherited in the child class but the properties of
child class will never get inherited in the parent class.

Using the parent class reference variable, we can access only parent class members but not
child class member. Using child class reference variable we can access both parent class
member as well as the child class member.

Terminologies

Parent class

Parent class is also known as super class or base class.


Parent class is used to achieve generalization.
Child class

Child class is also known as sub-class or derived class.


Child class is used to achieve specialization.

Types of inheritance

1) Single level inheritance

If inheritance is only for one level, known as single level inheritance.

Example - class Parent {


int a;
}
class Child extends Parent{
int b;
public static void main(String[ ]args) {
}
}

2) Multi level inheritance

If the inheritance has more than one level, it’s known as multi level inheritance.

Example - class A1 {
String s1;
}
class B1 extends A1{
String s2;
}
class C1 extends B1{
String s3;
}
class D1 extends C1{
String s4;
}
Way - 1

Way - 2
Way - 3
3) Hierarchical inheritance

If a parent class has more than one child class at the same level, it’s hierarchical inheritance.

Example - class A1{


String s1;
}
class B1 extends A1{
String s2;
}
class C1 extends A1{
String s3;
}

4) Multiple inheritance

If a child class has more than one parent at the same level, it’s multiple inheritance.

Example - class A1{


Public void m1(){
}
}
class B1{
Public void m1(){
}
}
class C1 extends A1, B1{
C1(){
super();
}
public static void main(String[ ] args {
C1 ch=new C1();
Ch.m1()
}
}

In Java multiple inheritance cannot be achieved with the help of classes.


Assume there are classes A1 and B1, and both have the same method with the same
signature.
Now class C1 extents both A1 and B1. If we create object for class C1 our compiler will
add a default No argument constructor inside the very first statement is a super() call
statement.
The job of a super() call statement is to call the constructor of parent class. There are two
parents A1 and B1 - which class constructor has to be called?
The constructor gets confused about which parent class constructor to call, hence this
leads to the ambiguity problem [diamond problem].

5) Hybrid inheritance
Hybrid inheritance is a combination of hierarchical inheritance and multiple inheritance
This is also not supported for Java (in class) due to diamond problem in multiple
inheritance

Example - class P1 {
String s;
}
class A1 extends P1{
String s1;
}
class B1 extends P1{
String s2;
}
class C1 extends A1, B1{
String s3;
}

The output would be a compile time error.


Super() Call Statement

Super is a keyword which is used to access the members of parent class.


Super() statement is used to call the constructor of parent class from child class.
Purpose of super() Call statement

To load all the non static member of parent class into the object created.
With the help of super() call statement we can pass data to non static members of a
parent class from the child class.

Rules for using super() call statement

It should be the first statement inside the constructor.


We should only use one super() call statement inside a single constructor.
Using multiple super() call statements inside a single constructor is not possible.
If a programmer fails to add a super() call statement inside the constructor then compiler
adds no argument super() call statement implicitly.
Understanding reference variable

A single object can be referred through multiple reference variables.

Note
We can access the member of student object by using the reference variable S1 or S2 or
S3 because all three reference variables are pointing to the same object.
We can copy the reference of one variable to another variable only when both the
variables are the same data type.
In case both reference variables are of different data types then we need to convert from
one reference to another reference .

Non Primitive type casting

The process of converting one type of object reference to another type of reference is
known as non primitive type casting.
Also known as derived type casting.

Rules to achieve Non Primitive Type Casting

To convert one type of object reference to another type of reference, there should exist
IS-A relationship.
Or there should exist a common child.(Multiple inheritance)

Types of Non-Primitive typecasting

There are two types of non primitive typecasting:


1) Upcasting
2) Downcasting

Upcasting

The process of converting child type reference variable to parent type reference variable
is known as upcasting.
Example: Child ch=new Child();
Parent p1=ch; //upcasting
(Or) The process of creating an object for child and store it in parent type reference
variable is known as upcasting.
Example: Parent p1=new Child(); //upcasting
Once the reference variable gets upcasted using upcasted reference variable, we can
only access parent class member, not the child class members. (Disadvantage)
If we try accessing child class members using parent type reference variable, we get
compile time error.
Upcasting can be performed implicitly by our compiler.
We can perform Upcasting using type caste operator as well.

Why do we need upcasting?

Using upcasting we can achieve generalization. (common)


When we create generalized container, we can store any type of child class object
reference into it .
Parent class is always consider as a generalized class.
Parent type reference variable is used to create the generalized container.
Downcasting

The process of converting parent type reference variable to child type reference variable
is known as downcasting.
Downcasting cannot be done implicitly by the compiler we need to perform down casting
explicitly using typecast operator.
Advantage of downcasting: we can access child class members.
ClassCastException

Example - Parent p1=new Parent();


Child ch=(Child)p1; //downcasting

It is a runtime exception.
During downcasting we get ClassCastException which stops the program abnormally.

When do we get the ClassCastException?

When we try to convert a reference variable to specific type (class), if the object does not
contain the instance of that particular type then we get a ClassCastException .
We can verify whether the object contain the instance of that particular type or not by
using instanceof operator.

instanceof = keyword, it is a binary operator.

Syntax
referenceVariable instanceof ClassType;

Case 1: Parent p1=new Child();//upcasting


System.out.println(p1 instanceof Child); //true
Child ch=(Child)p1;//downcasting is possible

Case 2: Parent p1=new Parent();


System.out.println(p1 instanceof Child); //false
Child ch=(Child)p1;//downcasting is not possible

Note
The return type of instanceof operator is boolean.
If the object contain instance of that particular type then instance of operator will return
true, if not present it will return false.
You can only downcast an object if it was originally an instance of the child class.
In your case, p1 is an instance of Parent, not Child.
So, Child ch = (Child) p1; is invalid because p1 is not actually a Child instance.

What Happens at Runtime?

Java will allow the explicit cast (Child) p1; at compile time.
But at runtime, when Java tries to cast p1 (which is purely a Parent object) to Child, it will
fail and throw:
Exception in thread "main" java.lang.ClassCastException: methodPro.Parent cannot be
cast to methodPro.Child
Instance of
Polymorphism
The word polymorphism is derived from two different Greek words:
poly = many/ various/numerous
morphism = forms/behavior
Polymorphism is the ability of an object to behave in many ways.
There are two types of polymorphism :
Compile time polymorphism
Runtime polymorphism

Compile Time Polymorphism

If the association between method called statement and the method declaration
statement is achieved to during compile time and same behavior is executed is known as
compile time polymorphism.
It is also known as static polymorphism.
We can achieve compile time polymorphism by the following ways :
1) Method Overloading
2) Constructor Overloading
3) Method Shadowing
4) Variable Shadowing
5) Operator Overloading (not supported by Java)

1) Method Overloading
If a class has more than one method with same name but different formal argument, it’s
known as method overloading.
Method overloading can be achieved with both static and non-static methods.
We can achieve method overloading in two ways:
1) by changing number of arguments.
2) by changing data type of arguments.

1) Example of changing number of arguments


2) Example of changing data type of arguments.

Method overloading is always based on method name and formal argument, but not on
return type of method.

Method overloading with type promotion

For method overloading, if no suitable method is found - compiler tries to perform type
promotion. If type promotion is available, the respective method is called, if not - we get
a compile time error.
Type promotion is possible in case of widening but not in case of narrowing.
CTE

Type promotion will be always done by the compiler to the nearest data type.
CTE (Ambiguity error)

In case of type promotion if there exists more than one method, we get Ambiguity error.

Q) Can we overload main method?


Yes we can overload main method but our JVM will call the main method which
accepts String[] args.
(SUPPOSED TO BE CTE BUT GETTING AN OUTPUT FOR SOME REASON)

CTE
CTE

3) Method shadowing
If the parent class and child class have the same static method with same method
declaration, it’s known as method shadowing.
Method shadowing is example of compile time polymorphism.
In method shadowing, all the methods should be static.
In method shadowing, the method gets executed based on the reference variable data
type.
4) Variable shadowing
If the parent class and child class have same variable with the same name, it’s variable
shadowing.
Variable shadowing can be achieved using both static variable as well as non static
variable.
Variable shadowing is an example of compile time polymorphism.
In case of variable shadowing the value will be used based on the reference variable type.
Runtime Polymorphism

The association between method call statement and the method declaration statement
which happens during runtime (execution of a program) is known as runtime
polymorphism.
It is also known as dynamic polymorphism.
Run time polymorphism can be achieved with the help of method overriding.

Method Overriding

Changing the implementation of parent class method inside the child class is known as
method overriding.
If the parent class and child class contain the same non static method with the same
declaration it’s known as method overriding.
Rules for achieving method overriding

IS-A relationship should be there. (parent and child)


The method which we are overriding, should be non static.
The method declaration should be same in both parent class and the child class .
The access modifier should be same or it should have higher accessibility.
private -> default -> protected -> public
In case of method overriding, the method gets executed based on the run time object.
Abstraction
Abstraction is a process of hiding the background details by providing only the essential
features or important features.
It is a process of hiding the method implementation by showing only the functionality
(method declaration) to the user.

How do we achieve abstraction in Java?

Using abstract classes and interfaces.


We can achieve abstraction by using abstract keyword.

Abstract

Abstract is a keyword, it is a modifier.


We can prefix abstract keyword only for methods and the classes (not for variables and
stuff).

Abstract method
Any method which is prefix with the abstract modifier is known as abstract method.
Abstract methods are incomplete methods because they do not contain any method
implementation.
Syntax - [Access Modifier] [Modifier] returntype methodName([formal argument]);

Abstract Class

Any class which is prefixed with abstract keyword is known as abstract class.
If a class contains at least one abstract method or more than one abstract method, we
should make the classes abstract.
If a class does not contain any abstract methods then making the class abstract is
optional.

Note

Abstract class can contain both concrete and abstract methods.


Hence main method is a concrete method which can be declared inside the abstract
class.
If any class contains main method, it is eligible for execution, therefore we can execute
abstract class as well.
We cannot create the object for abstract class.
We can create reference variable type.
If a class contains at least one abstract method either declared or inherited then we must
make the class abstract.
We cannot create object for abstract class but we can create reference variable.

Concrete class

The class which is not prefixed with abstract keyword.


Concrete class doesn’t contain any abstract methods.
We can create object for concrete class.

Concrete method

The method which is not prefixed with abstract keyword is known as concrete method.
Concrete methods always contain implementation.

Implementation of abstract method

If a class is inheriting an abstract class, child class should provide implementation for all
the abstract methods of parent class.
In case the child class doesn’t provide implementation for abstract method of parent
class, it is mandatory to make the child class as abstract.
Steps to provide implementation for abstract method

Using inheritance, make a child class to abstract class.


Using method overriding, provide implementation for all the abstract methods of parent
class.
Interface

It is a keyword, non-primitive datatype.


Interface is a component of java which is used to achieve 100% abstraction.

Syntax

[Access Modifier] interface InterfaceName {


//statements;
}

Note - When we compile an interface, .class file gets generated.


InterfaceName.java -> javac -> InterfaceName.class

What are all the members that can be declared inside an interface?

In interface by default the access modifier is specified as public.


Static methods are allowed inside interface, hence we can create main() method and can
execute interface as well.
Variable implicitly gets considered as final static.
Final variable must be initialized at the time of declaration as default values are not
applicable
Final variable cannot be re-initialized.
We can create reference variable for interface.
We cannot create object for interface (constructors are not allowed).
We cannot create initializers.
Only non static abstract methods are allowed and these can be declared without having
abstract as a modifier because it will implicitly get considered as abstract.
Non static concrete methods are not allowed.

Why do we need interface?

By using interface, we can achieve 100% abstraction.


Using interface we can provide solution for diamond problem, therefore we can achieve
multiple inheritance with the help of interface.
What are all the members which will not get inherited from an interface?

From an interface static method will never get inherited to the class or interface.

Class extends Class (possible)


Interface extends Interface (possible)
Interface implements Class (not possible)
Class implements Interface (possible)
Class extends Interface (not possible)

Inheritance with respect to interface

An interface can inherit any number of interfaces at the same time with the help of extends
keyword.

CTS

When an interface is inheriting from another interface, child interface need not provide
implementation for abstract methods of parent interface.
Interface can inherit any number of interfaces at the same time(multiple inheritance).

CTS

Using interface we don’t get diamond problem, hence we can achieve multiple inheritance
using interface.
Reason

Interface doesn’t contain any constructor.


Non static concrete methods are not allowed in an interface, therefore non static method
are abstract.
Static concrete methods will never get inherited from an interface.

CTS
Solution to Diamond Problem:

You might also like