Object Oriented Programming (2)
Object Oriented Programming (2)
May 2024
Addis Ababa,
Ethiopia
Chapter One: Object Oriented The Java platform consists of:
Programing the Java VM
1.1. Overview the Java API
Object oriented programming: allow the (Application
programmer to break down the problem into Programming
objects. Interface).
Objects: self-contained entities consisting of The API provides libraries, which
both data and operations together. groups a number of related classes
E.g. java, C++, C#, VB6, Python… and interfaces together into what is
called a Java package.
OOP: is a programming language model
organized around objects rather than 1.2. Fundamentals of Objects and
"actions" and data rather than “logic”. Classes
Java technology consists of an OO Programming Paradigms፡
programming language and a platform on 1. Procedural Programming:
which programs can be run. (remember)
4|Page
single line comment //, 2 multiline 3. Whitespace in Java is used to
comments /* …. */ and /** ….*/. separate the tokens in a Java source
The las one is used by javaDoc file. it is required in some places,
2. Token is the smaller individual units such as between access modifiers,
inside a program the compiler type names and Identifiers, and is
recognizes when building up the used to improve readability
program. elsewhere.
There are five types of Tokens in Java whitespace consists of the
Java:
a. Space character ' ' (0x20),
Reserved keywords: class,
extends, implements, for… b. The tab character (hex
0x09), (\t)
Identifiers: programmers
given name; grade, c. The line separators
gRade… characters newline(\n) (hex
0x0a)
Literals (Constants values):
55, 60.78, “Hi”, „M‟… Java d. The carriage return (hex
language specifies five major 0x0d) characters(\r)
types of literals => integer, e. The form feed character (hex
floating, character, string & 0x0c), (\f) : produce
Boolean literals
1.3. Variables in Java
Operators: Are symbols that
Variable = Data Type + Identifier
take one or more arguments
(operands) and operates on There are three kinds of variables in Java:
them to produce a result. An
A. Local variables:
operator performs a function
on one (Unary), two (Binary), Local variables are declared in
or three operands (Ternary). methods, constructors, or blocks.
Java has one ternary operator,
has only local scope
?:, which is a short-hand if-
else statement. E.g. c=x?w:s; Access modifiers cannot be used
Operators can be Arithmetic, for local variables.
Logical, assignment,
They are visible only within the
Relational, conditional,
Increment, declared method, constructor, or
block.
Separators: symbols used to
indicate where groups of Have not a default value
codes are divided and Should be declared and
arranged. E.g. () , {}, [] , ; , , , initialized @ z first time.
.
Declare before use anywhere in
a method or block.
5|Page
Other methods in the class NB: By default, a member declared
aren't even aware that the within a class is an instance member.
variable exists.
C. Class/Static variables
E.g. if(x > 100) {
String s1 = “Hello"; } Are declared with the static
keyword in a class, but outside a
String a=s1 + method, constructor or a block.
“Java” // Is this
valid? There would only be one copy
of each class variable per class,
You cannot use s1 outside of that regardless of how many objects
if block. are created from it.
Created when method or Are rarely used other than being
constructor is entered. declared as constants. (public
static final)
Destroyed on exit.
Are stored in the static memory.
B. Instance variables:
Static variables are created when
Are declared in a class, but
the program starts and destroyed
outside a method, constructor or
when the program stops.
any block.
Visibility is similar to instance
Have default values.
variables. However, most static
are variables which are bound to variables are declared public
the object itself. Meaning=>
Default values are same
Every instance of that class as instance variables.
(object) has it's own copy of
Static variables can be
that variable
accessed by calling with the
Are created when an object is class name
created with the use of the ClassName.VariableName.
keyword 'new' and destroyed
When declaring class variables
when the object is destroyed.
as public static final, then
Can be declared in class level variable names (constants) are all
before or after use. in upper case.
Recall Static Methods
Access modifiers can be
given for instance variables. Data Type
Are visible for all methods, It refer to an extensive system used
constructors and block in the for declaring variables or functions
class. of different types.
The type of a variable
E.g. class MyClass
determines how much space it
{ float aFloat; }
occupies in
6|Page
storage and how the bit pattern stored is Widening conversion usually
interpreted. occur automatically.
Java has two basic data types Example: int f = 9;
1. Primitive Data Types: are 8 in java float g = f;
(byte, short, int, long, float, double, long l=560; float f =
char & Boolean) l; //no explicit
2. Reference types: Arrays, type casting
classes, and interfaces, String) required
Note: Boolean type has a value true or 2. Narrowing (Explicit)
false (there is no conversion b/n Casting: if you want to
Boolean and other types).
narrow or go in the other
All non-primitive types are reference direction, Java won‟t do
types, so all class types are reference that automatically. You
types. have to do that
programmatically.
All integers in Java are signed, Java
doesn‟t support unsigned integers.
Type casting
Assigning a value of one type to a
variable of another type is known Syntax: smallerDT
as Type Casting. var=(smallerDT)largerDTVar
OR largerValue;
In Java, type casting is classified
into two types Example: float y=78.9f; byte b =
(byte)y; //explicit type
1. Widening, (Implicit) or casting required
Automatic Casting: Java
supports automatic int x = (int)2.7; double d =
widening, a kind of 100.04; long l = (long)d;
conversion from one type to Question: What is the
another which doesn‟t lose merit and demerit of
information. implicit and explicit type
casting?
Boxing and Unboxing:
Autoboxing is the automatic
conversion that the Java compiler
Two conditions for automatic makes between the primitive
casting types and their corresponding
object wrapper classes.
Types are compatible
Destination is For example, converting an int to an
wider than the Integer, a double to a Double, and so
source on.
7|Page
If the conversion goes
the other way, this is
called unboxing.
8|Page
Converting primitive data types into Iteration: The for(), while() and
object is called boxing. do…while() statements
Therefore, while using a wrapper 4. Jumping Statements: to jump out
class you just need to pass the value of loops and to control other areas
of the primitive data type to the of program java uses break and
constructor of the Wrapper class. continue statements.
And the Wrapper object will be The break statement: used to exit a
converted back to a primitive data loop
type, called unboxing. The Continue Statement: used to force
program to go back to the top of a
The Number class is part of the loop
java.lang package. Labels: Java does not include a goto
statement.
Overview of Java statements
Instead of goto, Java allows you to
Statements are roughly equivalent
combine break and continue with a
to sentences in natural languages.
label.
A statement forms a complete unit
of execution.
There are three kinds of statements:
1. Expression statements: Perform
computations and return values. It is
a series of variables, operators, and
method calls that evaluates to a
single value. (constructed according
to the syntax of the language). There
are:
A. Assignment expressions,
C. Any use of ++ or -
-,
B. Method calls,
D. Object creation
expressions ,
2. Declaration statements: declares/
Introduces a very first variables
E.g. double c = 8.4;
3. Control flow statements:
regulates the order of statements
execution
Selection: the if() and switch()
statements
9|Page
Chapter Two: Classes and for another.
Objects
2.1. Fundamentals of Classes
A class is a blue print from
which individual objects are
created.
Class is a template for an object,
and an object is an instance of a
class
Class is the logical construct upon
which the entire Java language is
built because it defines the shape
and nature of an object.
As such, the class forms the basis
for object-oriented programming in
Java.
Classes usually consist of two things:
instance variables and methods
Any concept you wish to
implement in a Java program must
be encapsulated within a class.
A sample of a class is given below:
class Dog {
13 | P a g e
class DogDemo { // This = new Dog(); //
class declares an object of allocate a Dog object
type Dog.
public static void Methods
main(String args[]) { Dog Are members of classes and do
myDog = new Dog(); operations.
String doginfo; //used to
hold new Dog‟s attribute Allows different classes to
myDog.age = 10; communicate each other.
myDog.breed=“Australian E.g. type
Cattel Dog”; myDog.color name(parameter- list)
= “Red”; //assign values to { // body of method
doginfo= “ Breed: ” + //….
myDog.breed + “Dog„s return value; // if
age:” + myDog.age +
type is not void
“Color: ” + myDog.color;
System.out.println(“The dog‟s " + doginfo);
}}
Declaring Objects
When you create
a class, you are
creating a new
data type.
You can use
this type to
declare objects
of that type.
the following is
used to declare an
object of type
Box:
Dog
myDog =
new
Dog(); OR
Dog
myDog; //
declare
reference/te
mplate to
object
myDog
14 | P a g e
} return a*a; } }
Read About Methods…
Returning a Value
Methods…Adding a method that takes
parameters
Method Overloading
Is a process of having the same
name for different methods as long
as their parameter list or data types
in the parameter list is different?
The return type alone is
insufficient to distinguish two
versions of a method.
Parameters are key identifiers
of OM.
Is one of the ways that Java
supports polymorphism
Java‟s automatic type conversions
can play a role in overload
resolution.
Exammple: // Demonstrate
method overloading.
class OverloadDemo {
void test() {
System.out.println("No
parameters"); }
void test(int a) { //
Overload test for one integer
parameter.
System.out.println("a: " +
a); } void test(int a, int b)
{ // Overload test for two
integer parameters.
System.out.println("a and b:
" + a + " " + b); }
double test(double a) { //
overload test for a double
parameter
System.out.println("double
a: "
+ a);
15 | P a g e
class Overload { ng class A {
public static void int i ,j;
main(String args[]) A ( int a, int b)
{ { i= a;
OverloadDemo ob = j= b;
new OverloadDemo(); }
double result; // display i and j
// call all void show ( ) {
versions of Sytem.out.println ( “ i and
test() j : “ + i
ob.test(); + “ “ + j );
ob.test(10); }
ob.test(10, }
20); class B extends A
result = ob.test(123.25); { int k;
System.out.println("Result of
ob.test(123.25): " + result);
}
}
Method Overriding
In a class hierarchy, when a
method in a subclass has the
same name and type
signature as a method in its
superclass, this is called
method Overriding.
the method in the
subclass is said to
override the method
in the superclass.
The Method in
the super class is
known as an
overridden
method which is
called within a
subclass.
The version of the
method defined by
the superclass will
be hidden.
E.g. :
//
Method
overridi
16 | P a g e
B ( int a, int b, int c) Once you define your own
{ super( a, b); constructor, the default constructor
k= c; is no longer used.
}
// display k – this Syntax:
overrides show( ) in A
void show ( ) Have the same name with their
{ System.out.println ( “ k : class name.
“ + k Have not return type, not even void.
);
} With curly brasses
}
Constructor example: page 22(Lab
class override {
Manual)
public static void main (
String args[ ] ) { Parameterized Constructors:
B subob = new B ( 1, 2, 3); similar with parameterized methods.
subob.show( ) ; // this Refer your lab manual..
calls show( ) in B;
} Overloading Constructors:
}
Reding Assignment
The output produced by this
program is shown here : The this Keyword:
k : 3
Constructors Instance Variable Hiding:
Performs automatic initialization of Garbage Collection:
objects. .:.
The finalize( ) Method:
Initializes an object immediately
upon creation. Overloading Constructors:
17 | P a g e
There is no explicit need to destroy Nested and Inner Classes
objects as in C++. A class within another
Garbage collection only occurs class known as nested
sporadically (if at all) during the classes.
execution of your program The scope of a nested class is
Returning Objects bounded by the scope of its
enclosing class.
A method can return any type of
data, including class types that The inner classes can access
you create. For example: instance variables of the outer
class but not vice versa.
Using objects as parameters:
There are two types of
Recursion nested classes: static and
Recursion is the attribute that non-static.
allows a method to call itself Static Class: must access the
A method that calls itself is members of its enclosing
said to be recursive E.g. class through an object(Not
directly). And are seldom
class Factorial {// A used
simple example of
recursion. None-Static Class: Called
// this is a recursive inner class and has access to
method all of the variables and
int fact(int n) { methods of its outer class
int result; if(n==1) return directly in the same way that
1; other non-static members of
result = fact(n-1) * n; the outer class do.
return result; } }
class Recursion Access Specifiers
{ public static void Access level modifiers determine whether
main(String args[]) { other classes can use a particular field or
Factorial f = new invoke a particular method.
Factorial();
System.out.println("Factori Their are four types access levels:
al of 3 is " + 1. No Modifier(Default): Visible to
f.fact(3)); the package(source file), and it is
System.out.println("Facto called package-private
ri al of 4 is " +
f.fact(4)); 2. Private: Visible to the class only.
System.out.println("Facto
ri al of 5 is " + 3. Public: Visible to the world.
f.fact(5)); 4. Protected: Visible to the
} } package and all subclasses.
18 | P a g e
But can be overloaded since they are
resolved using static binding by
compiler at compile time.
Note: main method is static, since it
must be accessible for an
application to run, before any
instantiation takes place.
// Example to illustrate
Accessing the Static
method(s) of the class.
Static methods and Final Variables class Monk{
A static method can access only public static String
static data. monkName = "";
public static void monk(String
A static method can call only name){
other static data (Static methods & monkName = name; } }
variables), but can not call a non- class RealMonk {
static data from it. public static void main
(String[] args)
Static method is belongs to the
Monk.monk(“Father
class and not to the object.
Shinodah"); // Accessing the
A static method can be static method monk() and
accessed directly by the class field by class name itself.
name and doesn‟t need any
object. System.out.println(Monk.monkName
); //Accessing the static method
i.e ClassName.methodName(args) monk() by using Object's
reference.
A static method cannot refer to Monk shinoda = new
"this" or "super" keywords in
anyway
Static methods are called Monk()
without creating an object of ; shinoda.monk(“is not
class.
dead")
They are referenced by the class ;
name itself or reference to the System.out.println(shinoda.mo
Object of that class. nkN ame); } }
//Output: Father Shinoda
They are stored in Permanent
is not dead
Generation space of heap (in
Static memory) Static methods and Final Variables…
In Java, when final keyword is used
Static methods can not be with a variable of primitive data
overridden. types (int, float, .. etc), value of the
variable cannot be changed.
19 | P a g e
E.g. public class Test
{
20 | P a g e
public static void The class whose properties are
main(String args[]) { inherited is known as superclass (base
final int i = 10; class, parent class).
i = 30; // Error
because i is final.}} Therefore, a subclass is a
Don‟t Confuse with Constants specialized version of a superclass.
The java final keyword can be It inherits all of the instance variables
used in various context: and methods defined by the
superclass and add its own, unique
1. final variable - A variable
elements.
declared as final prevents the
content of that variable The extends keyword: is the keyword
being modified used to inherit the properties of a
class. Below given is the syntax of
2. final method - A method
extends keyword.
declared as final prevents the
user from overriding that Sytax:
method class Super{
3. final class - A class .....}
declared as final cannot be
extended thus prevents class Sub extends Super{ }
inheritance
Chapter – Three:
Inheritance and class Calculation{
int z;
Polymorphism What is public void addition(int
Inheritance? x, int y){
Inheritance is one of the cornerstones z=x+y;
of object-oriented programming System.out.println("The
because it allows the creation of sum of the given
hierarchical classifications. numbers:"+z);
}
Inheritance is the process where one public void
class acquires the properties (methods Substraction(int x,int y){
and fields) of another. z=x-y;
System.out.println("The
A class that is inherited is called a
difference between the given
superclass. numbers:"+z);
The class that does the inheriting is } }
called a subclass.
public class My_Calculation
OR: The class which inherits the extends Calculation{
properties of other is known as
subclass (derived class, child class) and public void
21 | P a g e
multiplication(int
x, int y){
22 | P a g e
z=x*y; subOb.k = 9;
System.out.println("The
product of the given
numbers:"+z);
}
public static void
main(String args[]){
int a=20, b=10;
My_Calculation demo =
new
My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a,
b);
}}
Example 2
class A
{ int i,
j;
void showij()
{ System.out.println("i and
j: " + i + " " + j); } }
class B extends A {
int k;
void showk()
{ System.out.println("k: " +
k); } void sum()
{ System.out.println("i+j+k:
" + (i+j+k)); } }
class SimpleInheritance
{ public static void
main(String args[]) {
A superOb = new A();
B subOb = new B();
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents
of superOb: ");
superOb.showij();
/* The subclass has access
to all public members of its
superclass. */
subOb.i = 7; subOb.j = 8;
23 | P a g e
System.out.println("Co The superclass has no knowledge
ntents of subOb: "); of what a subclass adds to it.
subOb.showij();
subOb.showk(); Constructors are not members, so
System.out.println they are not inherited by
(); subclasses.
System.out.printl
n("Sum of i, j
and k in
subOb:");
subOb.sum(); }}
Types of inheritance
1. Simple/single
inheritance: is damn
easy to understand.
When a class extends
another one class only.
2. Multi-Level
inheritance: One can
inherit from a derived
class, thereby making
this derived class the
base class for the new
class.
3. Hierarchical
inheritance: One class
is inherited by many
sub classes.
24 | P a g e
But the constructor of the String barking(){
superclass can be invoked from the }}
subclass. //main{
Animal wild=new
Member Access and Inheritance
Animal(); Dog fries=new
Although a subclass includes all of
Dog(); wild=fries;
the members of its superclass, it Wild.show()// correct show()
cannot access those members of the is defined in Animal
superclass that have been declared Wild.breed=“Woo woo”// ERROR
as private. }
For example:
The super keyword
Since encapsulation is a primary
class A { attribute of OOP, Whenever a
int i; private int j; // subclass needs to refer to its
private to A immediate superclass, it can do so by
void setij(int x, int y) { use of the keyword super.
i = x;
j = y; Super has two general forms.
}}
// A's j is not accessible 1. Used to access parent class
here. class B extends A { instance members.
int total; void 2. Used to access parent class
sum() { constructor.
total = i + j; // ERROR, j is
not accessible here 1. Used to access parent
}} class instance members.
class Access { super acts somewhat like this, except
public static void that it always refers to the superclass
main(String args[]) { of the subclass in which it is used.
B subOb = new B();
subOb.setij(10, 12); Super has the form: super.member
subOb.sum(); Here, member can be either a method or
System.out.println("Total is an instance variable.
" + subOb.total);
}} Super is most applicable to
resolve member hiding.
26 | P a g e
System.out.println("This is
display1 method");
}}
class MultiLevelDemo
extends SuperClass1
{
public static
void main(String args[])
{
MultiLevelDemo
object = new
MultiLevelDemo();
object.display1();
object.display2(
);
object.display3(
);
Output: extends SuperClass2
animal is created {
dog is created public void display1()
If you need more: Search on {
https://www.javatpoint.com/super-keyword
class SuperClass3
{
public void
display3()
{
System.out.println("This is
display3 method");
} }
class SuperClass2
extends SuperClass3
{
public void
display2()
{
System.out.println("This is
display2 method");
} }
class SuperClass1
27 | P a g e
} } {
When Constructors Are Called? System.out.println("Inside A's
constructor.");
In a class } }
hierarchy, // Create a subclass
constructors are by extending class A.
called in order of class B extends A {
derivation, from B() {
superclass to System.out.println("Inside B's
subclass. constructor.");
Further, since
super( ) must be
the first statement
executed in a
subclass‟
constructor, this
order is the same
whether or not
super( ) is used.
If super( ) is not
used, then the
default or
parameter less
constructor of each
superclass will be
executed. Why?
// Demonstrate
when constructors
are called. Create
a super class.
c
l
a
s
s
A
(
)
28 | P a g e
}} i = a;
// Create another subclass by j = b; }
extending B. // display i and j
class C extends B { void show() {
C() { System.out.println("i and j:
System.out.println("Inside " + i + " " + j);
C's constructor."); }}
}} class B extends A {
class CallingCons { int k;
public static void B(int a, int b, int c)
main(String args[]) { { super(a, b);
C c = new C(); k = c; }
}} // display k – this overrides
What is the output of this show() in A
program? And How void show()
Output: { System.out.println("k: " +
Inside A‟s Constructor k);
Inside A‟s Constructor }}
Inside A‟s Constructor class Override {
Method Overriding public static void
main(String args[]) {
In a class hierarchy, when a method in a
B subOb = new B(1, 2, 3);
subclass has the same name and type
subOb.show(); Which method
signature as a method in its superclass, is called? // this calls
then the method in the subclass is said to show() in B
override the method in the superclass. }}
When an overridden method is Output:
called from within a subclass, it will K: 3
always refer to the version of that
method defined by the subclass. class A
{ int i,
The version of the method defined by j;
the superclass will be hidden. A(int a, int b) {
i = a;
Method overriding occurs only when the
j = b; }
names and the type signatures of the two void show()
methods are identical. { System.out.println("i and
j: " + i + " " + j);
}}
What is the output of the class B extends A {
following program? int k;
// Method overriding. B(int a, int b, int c)
class A { { super(a, b);
int i, j; k = c; }
A(int a, int b) { void show() {
super.show(); // this calls
29 | P a g e
A's show()
30 | P a g e
System.out.println("k: " + class MyChildClass extends
k); MyBaseClass{
}} protected void disp(){
class Override { System.out.println("Chi
public static void ld class method");
main(String args[]) { }
B subOb = new B(1, 2, 3); public static void
subOb.show(); Which one is main( String args[]) {
called? // this calls show() MyChildClass obj = new
in B MyChildClass();
}} obj.disp();
Output: class method");
I and j: 1 2 }}
K: 3
Rules of method overriding in Java..
Argument list: The argument list of
overriding (method of subclass) and
Overridden (method of super class)
method must be similar.
The data types of the arguments
and their sequence should exactly
match.
Method names: must be similar.
private, static and final methods
cannot be overridden as they are local
to the class.
Access Modifier of the overriding
method cannot be more restrictive
than the overridden method of parent
class.
For example look the following
Program.
System.out.println("Parent
31 | P a g e
}}
Output:
Exception in
thread "main"
java.lang.Error:
Unresolved
compilation
problem: Cannot
reduce the
visibility of the
inherited method
from MyBaseClass
// The following
program can run
very well. But what
is the output?
class
MyBaseClass
{ protected
void disp()
{
System.out.println(
"Parent class
method");
}}
class MyChildClass
extends
MyBaseClass{
public void disp(){
System.out.p
rintln("Child
class method");
}
public static
void main( String
args[]) {
MyChildClass
obj = new
MyChildClass();
obj.disp();
}}
Output:
Child class method
32 | P a g e
Why Overridden Methods? When a parent class reference points to
The ability to define a behavior that's the child class object then the call to the
specific to the subclass type, which overridden method is determined at
means a subclass can implement a runtime, because during method call
parent class method based on its which method(parent class or child
requirement. class) is to be executed is determined by
The class can give its own specific the type of object.
implementation to an inherited method This process in which call to the
without even modifying the parent overridden method is resolved at
class code. runtime is known as dynamic method
This is helpful when a class has several dispatch.
child classes, so if a child class needs to Lets see an example to understand this:
use the parent class method, it can use
it and the other classes that want to
have different implementation can use
overriding feature to make changes
without touching the parent class code. class ABC{
//Overridden method
Method overriding is used for public void disp()
runtime polymorphism {
Example 2
// Dynamic Method Dispatch.
class A {
void callme()
{ System.out.println("Inside
A's callme method");
}}
class B extends A {
// override
callme() void
callme() {
System.out.println("Inside
B's callme method");
}}
class C extends A {
// override
callme() void
callme() {
System.out.println("Inside
C's callme method");
}}
class Dispatch {
public static void
main(String args[]) {
A a = new A(); // object of
type A
B b = new B(); // object of
type B
C c = new C(); // object of
type C
A r; // obtain a reference
of type A
r = a; // r refers to an A
34 | P a g e
r.callme(); // Syntax: abstract class class_name
calls A's version
of callme Example:
r = b; // r refers abstract class A
to a B object { abstract void
r.callme(); // callme();
calls B's version // concrete methods are
of callme still allowed in abstract
r = c; // r refers classes void callmetoo()
to a C object { System.out.println("This
r.callme(); // is a concrete method.");
calls C's version }}
of callme class B extends A
}} { void callme() {
Output: System.out.println("B's
Inside A's implementation of callme.");
callme }}
method class AbstractDemo {
Inside B's public static void
callme main(String args[]) {
method
Inside C's
callme
method
Abstract
Classes
A classes declared
with abstract
keyword and
can‟t be
instantiated.
Used to hide meaningless methods:
There can be no
objects of an abstract
class. .:.
An abstract class
cannot be directly
instantiated with
the new operator.
You cannot declare
abstract constructors,
or abstract static
methods
35 | P a g e
B b = new B(); // ...}
b.callme();
b.callmetoo();
A ob=new A()// ERROR }}
Using final with Inheritance
The keyword final has three uses.
1. To create the equivalent of a
named constant (final
variable)
- A variable declared as final
prevents the content of that
variable being modified.
2. To Prevent Overriding in
Methods (final method) - A
method declared as final
cannot be overridden.
E.g.
class A {
final void meth() {
System.out.println("Th
is is a final
method.");
}}
class B extends A
{ void meth() { //
ERROR! Can't
override.
System.out.println("Il
le gal!");
}}
3. To Prevent Inheritance in Classes
(final class) - A class declared as
final cannot be extended thus
prevents inheritance. It is illegal
to declare a class as both abstract
and final. E.g.
final class A {
// ...}
// The following class is
illegal.
class B extends A { //
ERROR! Can’t has subclass
A
36 | P a g e
Binding & final Methods: without body (no
Binding of overridden implementation)
methods happen at
Final:
runtime which is known
as dynamic binding. Class: declared as final prevents
inheritance.
The compiler is free to
inline calls to them Method: declared as final prevents
because it “knows” they overriding that method.
will not be overridden by
Variable: declared as final
a subclass.
prevents the content modification.
Normally, Java resolves
calls to methods
dynamically, at run time
called late binding.
However, since final
methods cannot be
overridden, a call to one
can be resolved at
compile time called early
binding.
Static Binding:
Dynamic Binding:
Multi-threaded
program contains two or
more parts that can run
concurrently.
Each part can handle
different task at the same
time making optimal use
of the available resources.
Especially, when your
computer has multiple
CPUs.
Summery:
Abstract:
Classes: declared
with abstract
keyword and can‟t
be instantiated.
37 | P a g e
Static: upon.
Method: can call only other
static data, belongs to class,
Can‟t b override.
Variable: declared with the static
keyword in a class, but outside a
method, constructor or a block.
Polymorphism
The dictionary definition of
polymorphism refers to a principle in
biology in which an organism or species
can have many different forms or
stages.
This principle can also be applied to
object-oriented programming like
the Java language
Polymorphism is the ability of an
object to take on many forms.
The most common use of polymorphism
in OOP occurs when a parent class
reference is used to refer to a child class
object.
Any Java object that can pass more than
one IS-A test is considered to be
polymorphic.
In Java, all Java objects are
polymorphic since any object will pass
the IS-A test for their own type and for
the class Object.
Polymorphism is derived from 2
Greek words: poly and morphs.
The word "poly" means many and
"morphs" means forms. So
polymorphism means many
forms.
polymorphism is the capability of an
action or method to do different things
based on the object that it is acting
38 | P a g e
It is one of the basic 2. Dynamic polymorphism
principles of object Dynamic (or late) method binding is the
oriented programming. ability of a program to resolve
Types of Polymorphism
There are
2 basic
types of
polymorphi
sm: references to subclass methods at
1. Static Polymorphism runtime.
1. Static polymorphism
Static Polymorphism is
in other words termed as
compile-time binding or
early binding.
Static binding occurs at compile time.
Method overloading is
a case of static binding
and in this case
binding of method call
to its definition
happens at the time of
compilation.
39 | P a g e
abstract class, each having their own speak() Test t= new Test();
method. System.out.println(t
Although each method reference is to an instanceof Test);
}}
Animal (but no animal objects exist), the
Output: True
program is will resolve the correct
method reference at runtime. The instance of operator-Down Casting
System.out.println(
"Sucessfull
Casting");
}
public
static void
show(Parent p){
if(p instanceof
Child){
Child
b1=(Child)p;
b1.check();
}}
public
static void
main(String[]
args){
Parent p=new
Child();
Child.show(p);
}} Output:
Sucessfull
Casting
41 | P a g e
How polymorphism supported in java You can create your own exception
Java has excellent support of classes by extending Throwable or
polymorphism in terms of a subclass of Throwable.
Inheritance, method overloading and
method overriding. Exceptions occur for various
reasons. E.g.
Method overriding allows Java to invoke
method based on a particular object at A user has entered invalid data.
run-time instead of declared type while A file that needs to be opened cannot
coding. be found.
Where to use polymorphism in code? A network connection has been lost
1. Method argument: in the middle of communications or
2. Variable names: the JVM has run out of memory.
3. Return type of method:
Some of these exceptions are caused by:
Chapter – Four: Exception User error,
Handling Programmer error,
“a person or thing that is excluded from
a general statement or does not follow a Physical resources that have failed in
rule.” some manner.
43 | P a g e
public static void doesn't exist, then a
main(String args[]){ FileNotFoundException occurs,
Scanner reader=new and compiler prompts the
Scanner(System.in);
programmer to handle the
exception.
System.out.println("Enter a
number :"); import java.io.File;
try { import
int num= java.io.FileReader;
reader.nextInt(); public class
FilenotFound_Demo { public
System.out.println("The static void
number is :" + num); main(String args[]){
} File file=new
catch File("E://file.txt");
(InputMismatchException e){ FileReader fr = new
FileReader(file);
System.out.println("There is }}
type mis match :"); If you try to compile
} the above program you
finally{ will get exceptions
like this.
System.out.println("This part C:\>javac
is always done"); FilenotFound_Demo.java
}} } FilenotFound_Demo.java:8:
Exception Types error: unreported exception
There two categories of Exceptions: FileNotFoundException; must
be caught or declared to be
1. Checked exception: Is an thrown
exception that occurs at the compile FileReader fr = new
time, FileReader(file);
1 error
These are also called as compile
Unchecked exceptions: Is an
time exceptions.
exception that occurs at the time of
These exceptions cannot simply execution, these are also called as
be ignored at the time of Runtime Exceptions.
compilation, These include programming bugs,
The Programmer should take such as logic errors or improper use
care of (handle) these of an API.
exceptions.
Runtime exceptions are ignored
For example, if you use at the time of compilation.
FileReader class in your
For example, if you have declared
program to read data from a file,
an array of size 5 in your program,
if the file specified in its
and trying to call the 6th element of
constructor
44 | P a g e
the array then an
ArrayIndexOutOfBou
ndsExceptione
xception occurs.
2. Other: Errors
45 | P a g e
Exception Vs Errors A stream is linked to a physical
1. Errors: An Error indicates device by the Java I/O system.
serious problem that a
Java implements streams within
reasonable application should
class hierarchies defined in the
not try to catch.
java.io package.
2. Exception: Exception
there are two kinds of Streams
indicates conditions that a
reasonable application InPutStream: The InputStream is
might try to catch. used to read data from a source.
Using try and catch… OutPutStream: the OutputStream is
used for writing data to a destination.
General form of try/catch:
Try{ 1. Byte Streams:
//block of code to monitor
for errors Java byte streams are used to
} perform input and output of 8-bit
Catch(ExceptionType1 exOb ) { bytes.
//handler for ExceptionType1 A byte stream is suitable for
}
processing raw data like binary
Catch(ExceptionType2 exOb ) {
files.
//handler for ExceptionType2
} The most frequently used classes are
, FileInputStream and
FileOutputStream.
File and Stream
A file is an object on a computer that import java.io.*;
stores data, information, settings, or public class
commands used with a computer CopyFile {
program. public static void
main(String args[]) throws
E.g. Image, text, video, IOException
audio…(Multimedia) {
In a graphical user interface (GUI) FileInputStream in = null;
FileOutputStream out =
such as Microsoft Windows, files
null;
display as icons that relate to the
try {
program that opens the file.
in = new FileInputStream("C:\\
A stream is an abstraction that either Users\\FIKR TE\\Documents\\text.txt");
produces or consumes information. out = new
FileOutputStream("C:\\Users\\FIK RTE\\
A stream is a communication channel Documents\\textCopied.txt")
that a program has with the outside ;
world. It is used to transfer data items int c;
in succession. while ((c = in.read())
!= -1) {
46 | P a g e
out.write(c); } The InputStream is used to read
}finally { data from a source and the
if (in != null) { OutputStream is used for writing
in.close(); } data to a destination.
if (out != null)
{
out.close(); } }}} Chapter – Five: Java Interface
2. Character Streams: An interface in java is a blueprint
of a class.
Java Character streams are used to
perform input and output for 16-bit It has static constants and
unicode. abstract methods.
48 | P a g e
// declare constant fields // declare methods */
that abstract // by default. public void method1();
} public void method2(); }
Example 2:
interface <interface_name>{ interface MyInterface{
/* compiler will treat
// declare constant fields // declare methods them as: public abstract
that abstract // by default. void method1(); public
} abstract void method2(); */
public void method1();
It provides total abstraction; public void method2(); }
class Demo implements
Means all the methods in interface MyInterface{
are declared with empty body and /* This class must have to
are public and all fields are implement both the abstract
public, static and final by default. methods else you will get
A class that implement interface compilation error */
public void method1(){
must implement all the methods
System.out.println("imp
declared in the interface.
le mentation of method1");
If a class implements an interface }
and does not provide method bodies public void method2(){
for all functions specified in the System.out.println("imp
interface, then class must be le mentation of method2");
declared abstract. }
public static void
Rules of Interface main(String arg[]){
Variables declared in an interface MyInterface obj = new
are public, static & final by default. Demo();
obj.method1();}}
Java does not allow you to extend Output:implementation of method1
more than one class, However
you can implement more than one Extending Interface
interfaces in your class. It is called Interface inheritance
51 | P a g e
obj.print();
obj.show();
Chapter – Six: GUI in JDBC
} }
Tagging Interface
An empty interface is known as tag
or marker interface.
For example Serializable,
EventListener, there are few
other tag interfaces as well.
These interfaces do not have any
field and methods in it.
You must be thinking if they are
empty why class implements
them? What‟s the use of it?
Class implements them to claim the
membership in a particular set.
Basically, Tag interfaces
are meaningful to the JVM
It would improve the readability of
your code.
The similarity b/n Interface & Class
An interface can contain any
number of method and fields.
It is written in a file with a .java
extension. With the name of the
interface matching the name of
the file.
The byte code of an interface
appears in a .class file.
The d/c b/n Interface & Class
You cannot instantiate an interface
Interface has not constructor
Methods in an interface are
all abstract.
Fields in an interface are all static
and final
An interface can extend multiple
interfaces
Summery
By default, methods in interface are
public and abstract.
Data members are public, static
and final.
An interface with empty body
is called Tag/marker interface.
52 | P a g e
53 | P a g e