Module 2
Module 2
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.
Classes
Classes fundamentals; Declaring objects; Constructors,
this keyword, garbage collection.
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.
• Another example can be to speak
something; for example, a cat speaks
meow, dog barks woof, etc.
• In Java, we use method overloading
and method overriding to achieve
polymorphism.
Classes
Classes fundamentals; Declaring objects; Constructors,
this keyword, garbage collection.
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
• 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.
Classes
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.
• An object in Java is the physical as well as a logical entity, whereas, a class in Java
is a logical entity only.
• 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.
Characteristics of Objects
• State: represents the data (value) of
an object.
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.
Assigning Objects Reference
variable
• In Java, objects are created dynamically on the heap memory, and reference
variables are used to hold the memory address of these objects
• . This concept of reference variables is fundamental to Java's approach to
object-oriented programming.
Assigning Objects Reference
variable
• Reference variable is a variable that holds the memory address of an
object rather than the actual object itself.
• It acts as a reference to the object and allows manipulation of its data
and methods.
• Reference variables are declared with a specific type, which
determines the methods and fields that can be accessed through that
variable
• When an object is created using the new keyword, memory is allocated
on the heap to store the object's data.
• The reference variable is then used to refer to this memory location,
making it possible to access and manipulate the object's properties
and behaviours
import java.io.*;
Class Demo {
int x = 10;
int display()
{
System.out.println("x = " + x);
return 0; Output
}
} Demo@214c265e
class Main { x = 10
System.out.println(D1); //point 2
System.out.println(D1.display()); //point 3
}
Introducing Method
A method is like a function which is used to
expose the behavior of an object.
Advantage of Method
• Code Reusability
• Code Optimization
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation(); Output:
s2.displayInformation(); 111 Karan
222 Aryan
}
}
• 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.
Example
Object and Class Example: Employee public class TestEmployee {
class Employee{ public static void main(String[] a
rgs) {
int id; Employee e1=new Employee();
String name;
float salary; Employee e2=new Employee();
void insert(int i, String n, fl Employee e3=new Employee();
oat s) {
id=i; e1.insert(101,"ajeet",45000);
name=n; e2.insert(102,"irfan",25000);
salary=s; e3.insert(103,"nakul",55000);
e1.display();
}
e2.display();
void display(){ e3.display();
Output:
system.out.println } 101 ajeet
(id+" "+name+" "+salary);} }
45000.0
102 Irfan
} 25000.0
103 nakul
55000.0
Object and Class Example:
Rectangle
Object and Class Example: Employee class TestRectangle1{
class Rectangle{ public static void main(Strin
int length; g args[]){
int width; Rectangle r1=new Rectangl
e();
void insert(int l, int w){
Rectangle r2=new Rectangl
length=l;
e();
width=w;
r1.insert(11,5);
} r2.insert(3,15);
void calculateArea() r1.calculateArea();
{System.out.println(lengt r2.calculateArea();
h*width);}
} Output:
} 55
}
45
Constructors in Java
Constructors, this keyword, garbage collection
Final: If you make any variable as final, you cannot change the value
of final variable (It will be constant).
The Java compiler provides a default The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.
The constructor name must be same The method name may or may not
as the class name. 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: copy the values of one object into another using Java
constructor Student6.java
• By constructor
• By assigning the values of one object into
Copyinganother
values without constructor
• copy
Bytheclone() method of Object class
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.
Student7.java
This keyword
This keyword
• In Java, this is a reference variable that refers to the current
object.
TestThis4.java
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.
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
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.
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.
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();
}
}
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:
// Constructor
public MyClass(int attribute1, String attribute2, double
attribute3) {
this.attribute1 = attribute1;
this.attribute2 = attribute2;
this.attribute3 = attribute3;
}
// More methods
}
Argument Passing
• Primitive variables are directly stored in stack memory.
the actual parameters are copied to formal arguments and these formal
• Each parameter consists of two parts: type name and variable name. A
type name followed by a variable name defines the type of value that can
parameter.
public class Sum {
public static void main(String[] args)
{
// Creating an object of class Sum.
Sum obj = new Sum();
/* Driver Code */
public static void main(String ar[])
{
SampleReturn1 obj = new SampleReturn1();
int result = obj.CompareNum();
System.out.println("The greater number among x and y is: " + r
esult);
}
}
Recursion
Recursion in java is a process in which a method calls itself continuously. A
method in java that calls itself is called recursive method.
Syntax:
can apply static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class.
• Block
• Nested class
Understanding Static
• 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.
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);
}
Output
public static void main(String args[]) 1
2
3
{
//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Introducing Final
The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
• Variable
• Method
• class
The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized final
variable.
It can be initialized in the constructor only.
The blank final variable can be static also which will be initialized in
the static block only..
Introducing Nested and Inner Classes
Defining a class within another class, such classes are known
as nested classes.
They enable you to logically group classes that are only used in one place,
thus this increases the use of encapsulation and creates more readable and
maintainable code.
static nested class: Nested classes that are declared static are called static
nested classes.
//code
class Java_Inner_class{
//code
}
• Nested classes represent a particular type of relationship that is it
• If all the class objects are a part of the outer object then it is easier
• That way all the outer class can access all the objects of the inner
class.
class TestMemberOuter1{
class Inner{
in.msg();
}
An object or instance of a member's inner class always exists within an object
of its outer class. The new operator is used to create the object of member
Syntax.
Outer Class Reference .new Member InnerClass Constructor();
obj.new Inner();
Inheritance: inheritance basics, using super, creating multi level hierarchy,
method overriding.
Inheritance in Java
• Inheritance in Java is a mechanism in which
one object acquires all the properties and
behaviors of a parent object.
• It is an important part of OOPs (Object Oriented
programming system).
• The idea behind inheritance in Java is that you
can create new classes that are built upon
existing classes. When you inherit from an
existing class, you can reuse methods and fields
of the parent class.
• Moreover, you can add new methods and fields
in your current class also.
• Inheritance represents the IS-A
relationship which is also known as a parent-
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be
achieved).
• For Code Reusability.
TestInheritance3.java
Why multiple inheritance is not
supported in java?
To reduce the complexity and simplify the language, multiple
inheritance is not supported inclass
java. A{
• Consider a scenario where void msg()
A, B, and C are three {System.out.println("Hello");}
classes. The C class inherits
A and B classes. If A and B }
classes have the same class B{
method and you call it from void msg()
child class object, there will {System.out.println("Welcome");}
be ambiguity to call the
method of A or B class. }
• Since compile-time errors class C extends A,B{//
are better than runtime suppose if it were
errors, Java renders
compile-time error if you
inherit 2 classes. So public static void main(String ar
whether you have same gs[]){
method or different, there C obj=new C();
will be compile time error.
obj.msg();//
Now which msg() method would be
Method Overriding in Java
If subclass (child class) has the same method as declared in
the parent class, it is known as method overriding in
Java.
Method Overriding in Java
• If a subclass provides the specific implementation of the
method that has been declared by one of its parent
class, it is known as method overriding.
• The run method in the subclass as defined in the parent class but
it has some specific implementation.
• The name and parameter of the method are the same, and there
is IS-A relationship between the classes, so there is method
overriding.
• Bike2.java
A real example of Java Method
Overriding
Test2.java
What is Overloading and
Overriding?
Note: super() is added in each class constructor automatically by compiler if there is no super() or
this().
The
java.lang.Throwable
class is the root class of
Java Exception hierarchy
inherited by two
subclasses:
Exception and Error.
Types of Java Exceptions
• There are mainly two types of exceptions: checked and
unchecked.
• An error is considered as the unchecked exception.
• However, according to Oracle, there are three types of
exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
Java Exception Keywords
Difference between Checked
and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.
For example, IOException, SQLException, etc. Checked exceptions
are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Handling Example
The rest of the code is not executed (in such case, the rest of the
code statement is not printed).
Solution by exception handling
}
The rest of the code is executed, i.e., the rest of the code statement is printed.
The code in a try block that will not throw an exception
TryCatchExample3.java
public class TryCatchExample3 {
}
Handle the exception using the parent class exception.
TryCatchExample4.java
public class TryCatchExample4 {
}
An example to print a custom message on exception
TryCatchExample5.java
public class TryCatchExample5 {
}
An example to resolve the exception in a catch block
TryCatchExample6.java
In this example, try block contains two exceptions. But at a time only one exception occurs
and its corresponding catch block is executed. MultipleCatchBlock2.java
MultipleCatchBlock3.java
Example to handle the exception without maintaining the order of exceptions (i.e. from most
specific to most general). MultipleCatchBlock5.java
Java finally block
TestThrow3.java