JAVA Unit 3 2023 Complete - Student
JAVA Unit 3 2023 Complete - Student
Inheritance
Inheritance basic - member access and inheritance - constructors and inheritance - using super to call superclass
constructors - using super to access superclass members - creating a multilevel hierarchy - superclass references
and subclass objects - method overriding - using abstract classes -using final - the object class.
What is Inheritance?
3
Excellence and Service
CHRIST
Deemed to be University
Base Class
Feature B
Feature C
Derived Class
Feature A
Feature B
4
Excellence and Service
CHRIST
Deemed to be University
5
Excellence and Service
CHRIST
Deemed to be University
6
Excellence and Service
CHRIST
Deemed to be University
7
Excellence and Service
CHRIST
Deemed to be University
TYPES OF INHERITANCE
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
8
Excellence and Service
SINGLE INHERITANCE
Parent Class
A
B Child Class
B Parent class
C Child Class
10
HIERARCHICAL INHERITANCE
A parent Class
D1 D2 D3
child Class 1 child Class 2 child Class 3
Alerts Setalerts()
12
● Now there are two classes one is car and another one is sport car. So we want to extend sport car class
to extract the features of car class.
13
PRACTICAL SESSION
OF
INHERITANCE
package inheritance;
Output:
class person{
void talk() talking...
{System.out.println("talking...");} earning...
}
class employee extends person{
void earn(){System.out.println("earning...");}
}
15
Can we create a object of parent class also or it will give
a error message.
16
Answer is yes we can create a object of parent class also
package basicprogsjava;
class person// base class
{ Output:
void talk()
{System.out.println("talking...");} talking...
} talking...
class employee extends person{ earning...
void earn(){System.out.println("earning...");}
17
Multilevel Inheritance
package inheritance;
class person{
void talk()
{System.out.println("talking...");}
}
class employee extends person{
void earn(){System.out.println("earning...");}
}
class student extends employee{
void study(){System.out.println("studing...");}
18
Super Keyword
● The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to
access the superclass constructor. The most common use of the super keyword is to eliminate the
confusion between super classes and subclasses that have methods with the same name.
19
Use of Super class
20
super is used to refer immediate parent class instance variable.
● We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields.
package inheritance;
class university1
{
String course="BCA";
}
class college1 extends university1
{
String course="BDA";
void printcourse()
{
System.out.println(course);
System.out.println(super.course);
}
}
class super1{
public static void main(String args[])
{
college1 d=new college1();
d.printcourse();
}}
21
super can be used to invoke parent class method
● The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as
parent class. In other words, it is used if method is overridden.
package inheritance;
class campus{
void course()
{System.out.println("BCA running");}
}
class christ extends campus{
void course(){System.out.println("BDA running");}
void subjects(){System.out.println("Object Oriented Programming using
java");}
void study(){
super.course();
course();
subjects();
}
}
class super2{
public static void main(String args[]){
christ obj=new christ();
obj.study();
}}
22
super is used to invoke parent class constructor.
● Do it by your own
23
Constructor in Inheritance
24
Scenarios
25
Constructor overloading in inheritance
package inheritance;
class base
{
base()
{
System.out.println("super class data");
}
base(int x)
{
System.out.println("super class constructor overloaded=" + x);
}}
class derived extends base
{
derived()
{
System.out.println("sub class data");
}
derived(int x, int y)
{
super(x);
System.out.println("sub class constructor overloaded=" + y);
}}
public class constC
{
public static void main(String[] args)
{
derived obj = new derived(10,20);
}}
26
Why Constructors can’t be inherited
Whenever a class (child class) extends another class (parent class), the sub class inherits state and
behavior in the form of variables and methods from its super class but it does not inherit
constructor of super class
● Constructors are special and have same name as class name. So if constructors were inherited
in child class then child class would contain a parent class constructor which is against the
constraint that constructor should have same name as class name.
● A parent class constructor is not inherited in child class and this is why super() is added
automatically in child class constructor if there is no explicit call to super or this.
27
Run time Polymorphism
28
Run time Polymorphism
package inheritance;
class university {
int x=10;
public void BDA()
{ System.out.println("Base BDA class"); }
public void BCA()
{ System.out.println("BCA class"); }
}
29
● university d = new college();
● Object is related to university so we can access function BCA() easily but not BBA()
30
Java Runtime Polymorphism with multilevel inheritance
● Try this
31
Method Overriding using abstract class
32
ABSTRACTION
33
Abstract Class
● We can’t create object of abstract class but we can create reference of abstract class.
● Abstract class contain at least one abstract method, it can have normal method also.
● Concreate class contain complete definition for all methods.
● like in the given diagram human have some property like breathing , thinking, eating that can be
inherited by female or male both , so there is no need to create a object of human
● A class which is declared with the abstract keyword is known as an abstract
class in Java. It can have abstract and non-abstract methods (method with the
body).
Human
Female Male
34
35
package abstraction;
abstract class govtpolicy {
abstract void retfile();
abstract void paytax();
void guidelines()
{
System.out.println("follow guidelines");
}}
class business extends govtpolicy {
void product() {
System.out.println("buy my product");
}
void retfile()
{
System.out.println("return your file on time");
}
void paytax()
{
System.out.println("tax is compulsory");
}}
class abstraction1 {
public static void main(String args[]) {
govtpolicy s = new business();
business b = new business();
s.guidelines();
s.retfile();
s.paytax();
}}
36
Can We Override a Static and Final Method?
● No, the Methods that are declared as final and static cannot be Overridden or hidden. For this
reason, a method must be declared as final only when we’re sure that it is complete.
• It is noteworthy that abstract methods cannot be declared as final because they aren’t complete
and Overriding them is necessary.
37
final with Class and Method
● The class cannot be subclassed. Whenever we declare any class as final, it means
that we can’t extend that class or that class can’t be extended, or we can’t make a
subclass of that class.
● If a class is declared as final as by default all of the methods present in that class are
automatically final, but variables are not.
Syntax:
Example:
1.char[] ch={‘S',’T',’U',’D',’E',’N',’T',’S'};
2.String s=new String(ch);
OR
String s=“STUDENTS";
39
Excellence and Service
CHRIST
Deemed to be University
string literal
If two or more strings have the same set of characters in the same sequence then they share
the same reference in memory
For example:
str3
40
Excellence and Service
CHRIST
Deemed to be University
New Operator
If two or more strings have the same set of characters in the same sequence then they share
the same reference in memory
For example:
My name is
String str1 = new String(“My name is Varuna”); str1
Varuna
String str2 = new String(“My name is Varuna”);
both the string references str1, str2 denote the different string object.
str2 My name is
Varuna
41
Excellence and Service
CHRIST
Deemed to be University
String is immutable
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is
created. For mutable strings, you can use StringBuffer and StringBuilder classes.
42
Excellence and Service
CHRIST
Deemed to be University
package stringfunc;
import java.io.*;
import java.lang.*;
class strfunc {
public static void main(String[] args) {
String mystr = "My Students";
System.out.println("String literal = " +mystr);
43
Excellence and Service
CHRIST
Deemed to be University
package stringfunc;
import java.io.*;
import java.lang.*;
class strfunc {
public static void main(String[] args) {
String mystr = "My Students";
String mystr1 = "My Students";
String mystr2 = new String(“My Students”);
System.out.println(”Result 1”+(mystr==mystr1));
System.out.println(“Result 2"+mystr.equals(mystr1));
System.out.println(”Result 3”+(mystr==mystr2));
System.out.println(“Result 4"+mystr.equals(mystr2));
}
}
44
Excellence and Service
CHRIST
Deemed to be University
In the above program we have created 3 objects of String class mystr , mystr1 and mystr2 . Mystr and mystr1 will be
created by string literals and mystr2 will be created by new keyword.
As we know using literals if we are creating String class objects with the same values then only one object will be created
and it will refer the same reference or address.
System.out.println(“Result 2"+mystr.equals(mystr1));
It will also return true because equal() will check the values not references
System.out.println(”Result 3”+(mystr==mystr2));
It will return False as the result because mystr and mystr2 are there at different references not at the same.
System.out.println(“Result 4"+mystr.equals(mystr2));
It will return true as the result because equal() will check the values that are same.
45
Excellence and Service
CHRIST
Java string Methods
Deemed to be University
46
Excellence and Service
CHRIST
Deemed to be University
47
Excellence and Service
CHRIST
Deemed to be University
CompareTo() –
48
Excellence and Service
CHRIST
Deemed to be University
CharAt()
package stringfunc;
public class charat1
{
public static void main(String ar[])
{
String s="Varuna";
System.out.println(s.charAt(0));
System.out.println(s.charAt(3));
}
}
49
Excellence and Service
CHRIST
Deemed to be University
Length()
package stringfunc;
public class charat1
{
public static void main(String ar[])
{
String s="Varuna";
System.out.println(s.length());
}
}
50
Excellence and Service
CHRIST
Deemed to be University
valueOf()
// Valueof() can convert all primitive datatype into string value and string value
into primitive data type expect char
package stringfunc;
public class valueof1 {
public static void main(String ar[])
{
int a=10; // conversion from Int to string
String s=String.valueOf(a);
System.out.println(s+10);
String str ="10"; // conversion from string to interger
int n2 = Integer.valueOf(str);
System.out.println(n2);
}
}
51
Excellence and Service
CHRIST
Deemed to be University
Trim()
Trim will remove the white space which appears before and after
the string
52
Excellence and Service
CHRIST
Deemed to be University
indexOf()
53
Excellence and Service
CHRIST
Deemed to be University
Output:
Christ
output of indexof char=4
output of indexof char from=4
output of indexof substring=2
54
Excellence and Service
CHRIST
Deemed to be University
Output:
Christ
output of lastindexof char=4
output of lastindexof char from=-1
output of lastindexof substring=2
55
Excellence and Service
CHRIST
Deemed to be University
Array of String
56
Excellence and Service
CHRIST
Deemed to be University
57
Excellence and Service
CHRIST
Deemed to be University
Java Encapsulation
Encapsulation is one of the key features of object-oriented programming. Encapsulation refers to the bundling of fields
and methods inside a single class.
It prevents outer classes from accessing and changing fields and methods of a class. This also helps to achieve data
hiding.
Note: People often consider encapsulation as data hiding, but that's not entirely true.
Encapsulation refers to the bundling of related fields and methods together. This can be used to achieve data hiding.
Encapsulation in itself is not data hiding.
58
Excellence and Service
CHRIST
Why Encapsulation
Deemed to be University
• In Java, encapsulation helps us to keep related fields and methods together, which makes our code cleaner and easy
to read.
• We can also achieve data hiding using encapsulation. In the given example, if we change the id , name and price
variable into private, then the access to these fields is restricted.
59
Excellence and Service
CHRIST
Deemed to be University
Read-Only class
//A Java class which has only getter methods.
public class student{
private String university=“CHRIST";
//getter method for college
public String getuniversity(){
return university;
}
}
In the above example Now, you can't change the value of the university data member which is
“CHRIST".
60
Excellence and Service
CHRIST
Deemed to be University
Write-Only class
//A Java class which has only setter methods.
public class student{
//private data member
private String university;
//getter method for college
public void setuniversity(String university){
this. university = university;
}
}
Now, you can't get the value of the university, you can only change the value of university data member.
61
Excellence and Service
CHRIST
Deemed to be University
Exception Handling
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
• The core advantage of exception handling is to maintain the normal flow of the application.
• Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the
code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is why we use exception handling
in Java.
62
Excellence and Service
CHRIST
Deemed to be University
Hierarchy of Java Exception classes
Checked
Checked
Checked
Unchecked
Unchecked
Unchecked
Unchecked
63
Excellence and Service
CHRIST
Deemed to be University
The throwable class provides a string variable that can be set by the subclasses to provide a detail message that provides
more information of the exception occurred.
All classes of throwables define a one parameter constructor that takes a string as the detail message
64
Excellence and Service
CHRIST
Deemed to be University
65
Excellence and Service
CHRIST
Deemed to be University
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.
66
Excellence and Service
CHRIST
Deemed to be University
Keyword Description
Try
The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or
finally.
Catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
Throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature
67
Excellence and Service
CHRIST
Deemed to be University
Four Ways
• Default throw and default catch(automatically run by java)
• Default throw and our catch
• Our throw and default catch
• Our throw an our catch
68
Excellence and Service
CHRIST
Deemed to be University
Arithmetic
Null Pointer
Number format
69
Excellence and Service
CHRIST
Deemed to be University
try {
// code
}
catch(Exception e) {
// code
}
Here, we have placed the code that might generate an exception inside the try block. Every try block is followed by a catch block.
When an exception occurs, it is caught by the catch block. The catch block cannot be used without the try block.
70
Excellence and Service
CHRIST
Deemed to be University
71
Excellence and Service
CHRIST
Deemed to be University
ArithmeticException
In the example, we are trying to divide a number by 0. Here, this code
class data{ generates an exception.
public static void main(String[] args) { To handle the exception, we have put the code, 5 / 0 inside the try block. Now
when an exception occurs, the rest of the code inside the try block is skipped.
The catch block catches the exception and statements inside the catch block is
try { executed.
If none of the statements in the try block generates an exception,
the catch block is skipped.
// code that generate exception
int divideByZero = 5 / 0;
// int divideByZero = x / y;(x and y can be entered from
keyboard)
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
System.out.println(“I am under catch block");
}
} 72
} Excellence and Service
CHRIST
Deemed to be University
package exceptionhandling;
public class morecatch {
public static void main(String[] args)
{
try
{
System.out.println(4/0);
System.out.println("in try block");
}
catch(NullPointerException e)
{System.out.println("Nullpointer exception:"+e.getMessage());
}
catch(ArithmeticException e)
{System.out.println("Arithmetic exception:" + e.getMessage()); }
System.out.println("last line");
}}
73
Excellence and Service
CHRIST
Deemed to be University
ArrayIndexOutOfBoundsException
public class prog3 {
74
Excellence and Service
CHRIST
Deemed to be University
NullPointer exception
75
Excellence and Service
CHRIST
Deemed to be University
We can also use the try block along with a finally block.
In this case, the finally block is always executed whether there is an exception inside the try block
or not.
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
finally {
System.out.println("Finally block is always executed");
}
}
}
76
Excellence and Service
CHRIST
Deemed to be University
In Java, we can also use the finally block after the try...catch block. For example,
77
Excellence and Service
CHRIST
Deemed to be University
Finally
package exceptionhandling;
public class morecatch {
public static void main(String[] args)
{
try
{
System.out.println(4/0);
System.out.println("in try block");
}
catch(NullPointerException e)
{System.out.println("Nullpointer
exception:"+e.getMessage());
}
catch(IndexOutOfBoundsException e)
{System.out.println("out of bound exception:" +
e.getMessage()); }
finally
{
System.out.println("last line");}
}}
78
Excellence and Service
CHRIST
Deemed to be University
79
Excellence and Service
CHRIST
Deemed to be University
Definition:
The throw and throws is the concept of exception handling where the throw
keyword throw the exception explicitly from a method or a block of code whereas
the throws keyword is used in signature of the method.
Point of usage:
The throw keyword is used inside a function. It is used when it is required to throw an
Exception logically.
The throws keyword is used in the function signature. It is used when the function has
some statements that can lead to exceptions.
Exceptions Thrown”
The throw keyword is used to throw an exception explicitly. It can throw only one
exception at a time.
The throws keyword can be used to declare multiple exceptions, separated by a comma.
Whichever exception occurs, if matched with the declared ones, is thrown automatically
then.
80
Excellence and Service
CHRIST
Deemed to be University
Example of Throw
package exceptionhandling;
import java.io.*;
class TestThrow {
public static void main(String[] args)
{
int balance=50000;
int fees = 70000;
try
{
if(balance<fees)
throw new ArithmeticException("not enough balance in your account");
balance = balance-fees;
System.out.println("transaction completed" + balance);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic exception:" + e.getMessage());
}
System.out.println("It will be cont.., because this is my catch");
}
}
81
Excellence and Service