Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Addis Ababa University

College of Natural and Computational Sciences


Department of Computer Science

Programming and Algorithms Module

Part I: Computer Programming


Part II: Object Oriented Programming
Part III: Design and Analysis of Algorithms
Part IV: Data Structure and Algorithms

May 2024
Addis Ababa,
Ethiopia
 The Java platform consists of:
Chapter One: Object Oriented  the Java VM
Programing
 the Java API
1.1. Overview (Application
Object oriented programming: allow the Programming
programmer to break down the problem into Interface).
objects.
 The API provides libraries, which
Objects: self-contained entities consisting of groups a number of related classes
both data and operations together. and interfaces together into what is
E.g. java, C++, C#, VB6, Python… called a Java package.

OOP: is a programming language model 1.2. Fundamentals of Objects and


organized around objects rather than Classes
"actions" and data rather than “logic”. Programming Paradigms፡
Java technology consists of an OO 1. Procedural Programming:
programming language and a platform on (remember)
which programs can be run.  is a list of step-by-step
The Java compiler translates the program instructions
into an intermediate language called Java  usually having a linear order of
bytecodes. execution.
Java bytecodes are platform-independent.  Includes C, C++, FORTRAN,
Guaranteed to be Write Once, Run Pascal, and Basic.
Anywhere. 2. Object oriented programming:
There are different Java interpreters for  allow the programmer to break
different platforms. down the problem into objects:
Java is: + Object Oriented + Platform  Easy to debugging.
Independent
 E.g. java, C++, C#, VB6, Python
+ Simple + Secure
3. Declarative:
+ Portable +
Multithreaded + Robust  Describe a problem rather than
defining a solution
Q1: What is the d/c between compiler and
interpreter?  Describes what something is like,
rather than how to create it.
 The Java platform is a bit different to
other platforms, in that it consists of ፩. Objects: (Recall)
software only – that means it is
 Are instances of a class
hardware-independent.

2|Page
 Are the basic runtime entities in ፭. Encapsulation:
an OO program.
 means the wrapping up of data and
 Are identifiable things or methods into a single unit (a class).
individuals?
 It also means that the data inside a
 Are of significance to the system class is hidden from everything
outside the class.
 Have states reflected in the
attributes (data) held about  The data can only be accessed by
the object invoking the methods of the class.
 Have characteristic behaviour  It is placing the data and the
(i.e. functionality) functions that work on that data in
the same place.
፪. Class:
፮. Inheritance:
 Is a blueprint for an object.
 It is the way in which objects of one
 is the definition of a set of objects
class get the properties of objects of
 which are all similar in terms of their another class(data &methods).
attributes
 For example, Person, employee and
 A class consists of a class name, data retiree
and methods.
 Inheritance provides the idea of
 e.g. customer class defines all reusability – the Person class can be
customer objects. reused without making changes to it,
because another class can be made to
፫. Members:
inherit from it.
 Collectively, the methods and  Types of Inheritance? read
variables defined within a class are
called members of the class. ፯. Polymorphism:

 These are local, instance and  The word polymorphism means the
Class/static variable ability to take more than one form.
፬. Abstraction:  In terms of the OOP, this means that
a particular operation may behave
 provides only essential information differently for different sub-classes
to the outside world.
of the same class.
 Or hiding their background details,
Components of java program
i.e., to represent the needed
information in program without Java program = Comments + Token(s) +
presenting the details. white space
 For example, a bank system. 1. Comments: Java supports three
types of comment delimiters. A

3|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, b. The tab character (hex 0x09),
extends, implements, for… (\t)
 Identifiers: programmers c. The line separators characters
given name; grade, gRade… newline(\n) (hex 0x0a)
 Literals (Constants values): d. The carriage return (hex
55, 60.78, “Hi”, „M‟… Java 0x0d) characters(\r)
language specifies five major
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, declared method, constructor, or
Increment, block.
 Separators: symbols used to  Have not a default value
indicate where groups of
codes are divided and  Should be declared and
arranged. E.g. () , {}, [] , ; , , , initialized @ z first time.
.
 Declare before use anywhere in a
method or block.

4|Page
 Other methods in the class aren't NB: By default, a member declared
even aware that the variable within a class is an instance member.
exists.
C. Class/Static variables
E.g. if(x > 100) { String
 Are declared with the static
s1 = “Hello"; }
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
 You cannot use s1 outside of that each class variable per class,
if block. regardless of how many objects
are created from it.
 Created when method or
constructor is entered.  Are rarely used other than being
declared as constants. (public
 Destroyed on exit. static final)
B. Instance variables:  Are stored in the static memory.
 Are declared in a class, but  Static variables are created when
outside a method, constructor or the program starts and destroyed
any block. when the program stops.
 Have default values.  Visibility is similar to instance
 are variables which are bound to variables. However, most static
the object itself. Meaning=> variables are declared public

 Every instance of that class  Default values are same as


(object) has it's own copy of that instance variables.
variable  Static variables can be accessed
 Are created when an object is by calling with the class name
created with the use of the ClassName.VariableName.
keyword 'new' and destroyed  When declaring class variables as
when the object is destroyed. public static final, then variable
 Can be declared in class level names (constants) are all in upper
before or after use. case.
Recall Static Methods
 Access modifiers can be given
for instance variables. Data Type
 It refer to an extensive system used
 Are visible for all methods,
for declaring variables or functions
constructors and block in the
of different types.
class.
 The type of a variable determines
E.g. class MyClass {
how much space it occupies in
float aFloat; }

5|Page
storage and how the bit pattern Widening conversion usually
stored is interpreted. occur automatically.
Java has two basic data types Example: int f = 9;
float g = f;
1. Primitive Data Types: are 8 in java
(byte, short, int, long, float, double, long l=560; float f =
char & Boolean) l; //no explicit type
2. Reference types: Arrays, classes, casting required
and interfaces, String)
2. Narrowing (Explicit)
 Note: Boolean type has a value true or Casting: if you want to
false (there is no conversion b/n Boolean narrow or go in the other
and other types). direction, Java won‟t do that
automatically. You have to
 All non-primitive types are reference
types, so all class types are reference do that programmatically.
types.
 All integers in Java are signed, Java
doesn‟t support unsigned integers.
Syntax: smallerDT
Type casting var=(smallerDT)largerDTVar
 Assigning a value of one type to a
OR largerValue;
variable of another type is known as
Type Casting. Example: float y=78.9f; byte
b = (byte)y; //explicit type
 In Java, type casting is classified into casting required
two types
int x = (int)2.7; double d =
1. Widening, (Implicit) or 100.04; long l = (long)d;
Automatic Casting: Java Question: What is the merit
supports automatic widening, and demerit of implicit and
a kind of conversion from explicit type casting?
one type to another which
doesn‟t lose information. Boxing and Unboxing:
 Autoboxing is the automatic
conversion that the Java compiler
makes between the primitive types
and their corresponding object
Two conditions for automatic wrapper classes.
casting  For example, converting an int to an
 Types are compatible Integer, a double to a Double, and so
 Destination is wider on.
than the source  If the conversion goes the other way,
this is called unboxing.

6|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
of the primitive data type to the program java uses break and
constructor of the Wrapper class. continue statements.
The break statement: used to exit a
 And the Wrapper object will be
loop
converted back to a primitive data
The Continue Statement: used to
type, called unboxing.
force program to go back to the top
 The Number class is part of the of a 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 to combine break and continue with a
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

7|Page
Chapter Two: Classes and  All methods have the same general
form as main( )
Objects
 However, most methods will not be
2.1. Fundamentals of Classes
specified as static or public.
 A class is a blue print from which
individual objects are created.  Java classes do not need to have a
main( ) method except the starting
 Class is a template for an object, and
point for your program.
an object is an instance of a class
 Further, applets don‟t require a main(
 Class is the logical construct upon
) method at all.
which the entire Java language is
built because it defines the shape and  A class defines a new type of data (it
nature of an object. is a reference type).
 As such, the class forms the basis for  In this case, the new data type is
object-oriented programming in called Dog.
Java.
 You will use this name to declare
 Classes usually consist of two things: objects of type Dog.
instance variables and methods
 a class declaration only creates a
 Any concept you wish to implement template; it does not create an actual
in a Java program must be object.
encapsulated within a class.
 To actually create a Dog object, use
 A sample of a class is given below: the second statement.
 Dog myDog; // Creates only
the template
 myDog = new Dog(); //
create a Dog object called
myDog
 After this statement executes,
myDog will be an instance of
Dog.
 Thus, it will have “physical”
reality .
 The code is contained within
methods (The operation is done 2.2. Types of classes
inside) ሀ. The Common types of classes:

 Thus, the data for one object is 1. Wrapper Class:- The eight
separate and unique from the data for classes of java.lang package
another.

8|Page
2. Abstract Class:- A classes 1. Supper Class: The class that
declared with abstract is inherited.
keyword and can‟t be
2. Sub Class: The class that
instantiated.
does the inheriting.
3. Final Class:- A class
መ. Based on the source file they are located
declared with final keyword
classes are classified in to two.
and can‟t be inherited.
1. Internal classes: Located at
4. Input-Output Class:-
the starting pointing file,
Available in java.io package.
includes main().
contains all the required
classes to perform I/O 2. External classes: Located in
operations a separate source file (outside
the starting pointing file).
5. String Class:- Immutable
Class created to manipulate
strings(Sequence of chars).
2.3. Source file declaration
6. System Class:- Contains rules
several useful class fields and
methods. It cannot be
instantiated. E.g. standard  These rules are essential when declaring
input, standard output, and classes, import statements and package
error output streams statements in a source file.
7. Mutable Class:- Have fields 1. There can be only one public
that can be changed. class per source file.
ለ. According to access modifiers: Classes 2. A source file can have multiple
are classified in to 4: nonpublic classes.
1. Public Classes: Accessible 3. The public class name should be
to the world the name of the source file as
well which should be appended
2. Private Class: Used only
by .java at the end.
inside a block(e.g with in the
outer class) For example: the class name is public class
Employee{} then the source file should be
3. Protected Class: Used in
as Employee.java.
parent class, package and
other subclasses  If the class is defined inside a
package, then the package statement
4. Default Class: Used only in
should be the first statement in the
parent class and package
source file.
ሐ. According to Inheritance: Classes are
 If import statements are present then
classified in to 2:
they must be written between the

9|Page
package statement and the class class DogDemo { // This class declares an
declaration. object of type Dog.
public static void main(String args[]) {
 If there are no package statements Dog myDog = new Dog();
then the import statement should be String doginfo; //used to hold new Dog‟s
the first line in the source file. attribute
myDog.age = 10;
 Import and package statements will
myDog.breed=“Australian Cattel Dog”;
imply to all the classes present in the myDog.color = “Red”; //assign values to
source file. doginfo= “ Breed: ” + myDog.breed +
 It is not possible to declare different “Dog„s age:” + myDog.age + “Color: ” +
import and/or package statements to myDog.color;
System.out.println(“The dog‟s " + doginfo);
different classes in the source file.
}}
2.4. Instantiating and
initializing class objects Declaring Objects
 Every Dog object will contain its  When you create a class, you are
own copies of the instance variables creating a new data type.
breed, age, and color.
 You can use this type to declare
 To access these variables, you will objects of that type.
use the dot (.) operator.
 the following is used to declare an
 The dot operator links the name of object of type Box:
the object with the name of an
instance variable.  Dog myDog = new Dog();
OR
 For example, to assign the age
variable of myDog the value 10, you  Dog myDog; // declare
would use the following statement: reference/template to object

myDog.age = 10; //This is called  myDog = new Dog(); //


instantiating a class. allocate a Dog object

 This statement tells the compiler to Methods


assign the copy of age that is  Are members of classes and do
contained within the myDog object operations.
the value of 10, breed to Australian  Allows different classes to
cattle dog, and color of red.... communicate each other.
 E.g. type name(parameter-
list)
{ // body of method
//….
return value; // if
class Dog {
type is not void
int age; String breed, color; }

10 | P a g e
} class Overload {
Read About public static void main(String
Methods…Returning a Value args[]) {
OverloadDemo ob = new
Methods…Adding a method that takes OverloadDemo();
parameters double result; // call all
Method Overloading versions of test()
 Is a process of having the same name ob.test(); ob.test(10);
ob.test(10, 20);
for different methods as long as their
result = ob.test(123.25);
parameter list or data types in the
System.out.println("Result of
parameter list is different? ob.test(123.25): " + result); }
 The return type alone is insufficient }
to distinguish two versions of a
method. Method Overriding
 Parameters are key identifiers of In a class hierarchy, when a method in a
OM. subclass has the same name and type
signature as a method in its superclass, this
 Is one of the ways that Java supports is called method Overriding.
polymorphism  the method in the subclass is said to
override the method in the
 Java‟s automatic type conversions superclass.
can play a role in overload  The Method in the super class is
resolution. known as an overridden method
which is called within a subclass.
 Exammple: // Demonstrate method
 The version of the method defined
overloading. by the superclass will be hidden.
class OverloadDemo {  E.g. :
void test() {
System.out.println("No // Method overriding
parameters"); } class A {
void test(int a) { // Overload int i ,j;
test for one integer parameter. A ( int a, int b) {
System.out.println("a: " + a); } i= a;
void test(int a, int b) { // j= b;
Overload test for two integer }
parameters. // display i and j
System.out.println("a and b: " + void show ( ) {
a + " " + b); } Sytem.out.println ( “ i and j :
double test(double a) { // “ + i
overload test for a double + “ “ + j );
parameter }
System.out.println("double a: " }
+ a); class B extends A {
return a*a; } } int k;

11 | P a g e
B ( int a, int b, int c) {  Once you define your own
super( a, b); constructor, the default constructor is
k= c; no longer used.
}
// display k – this overrides  Syntax:
show( ) in A  Have the same name with their class
void show ( ) { name.
System.out.println ( “ k : “ + k
);  Have not return type, not even void.
}
}  With curly brasses
class override {  Constructor example: page 22(Lab
public static void main ( String Manual)
args[ ] ) {
B subob = new B ( 1, 2, 3);  Parameterized Constructors:
subob.show( ) ; // this calls similar with parameterized methods.
show( ) in B; Refer your lab manual..
}
}  Overloading Constructors:
The output produced by this Reding Assignment
program is shown here :
k : 3  The this Keyword:
Constructors  Instance Variable Hiding:
 Performs automatic initialization of
objects. .:.  Garbage Collection:

 Initializes an object immediately  The finalize( ) Method:


upon creation.
 Overloading Constructors:
 Once defined, the constructor is
 Returning Objects:
automatically called immediately
after the object is created, before the  Recursion:
new operator completes.
 Introducing Nested and Inner
 The default constructor Classes:
automatically initializes all instance
Garbage Collection
variables to zero and all object
references to NULL.  The ability of deallocation of
memory automatically.
 The default constructor is often
sufficient for simple classes, but it  When no references to an object
usually won‟t do for more exist, that object is assumed to be no
sophisticated ones. longer needed, and the memory
occupied by the object can be
reclaimed.

12 | P a g e
 There is no explicit need to destroy Nested and Inner Classes
objects as in C++.  A class within another class
known as nested classes.
 Garbage collection only occurs
sporadically (if at all) during the  The scope of a nested class is
execution of your program bounded by the scope of its
enclosing class.
Returning Objects
 The inner classes can access
 A method can return any type of
instance variables of the outer
data, including class types that you
class but not vice versa.
create. For example:
 There are two types of nested
 Using objects as parameters:
classes: static and non-static.
 Recursion
 Static Class: must access the
 Recursion is the attribute that members of its enclosing
allows a method to call itself class through an object(Not
directly). And are seldom
 A method that calls itself is
used
said to be recursive E.g.
 None-Static Class: Called
class Factorial {// A
inner class and has access to
simple example of
all of the variables and
recursion.
// this is a recursive methods of its outer class
method directly in the same way that
int fact(int n) { other non-static members of
int result; if(n==1) return the outer class do.
1;
Access Specifiers
result = fact(n-1) * n;
Access level modifiers determine whether
return result; } }
class Recursion { other classes can use a particular field or
public static void invoke a particular method.
main(String args[]) { Their are four types access levels:
Factorial f = new
Factorial(); 1. No Modifier(Default): Visible to
System.out.println("Factori the package(source file), and it is
al of 3 is " + f.fact(3)); called package-private
System.out.println("Factori
al of 4 is " + f.fact(4)); 2. Private: Visible to the class only.
System.out.println("Factori 3. Public: Visible to the world.
al of 5 is " + f.fact(5));
} } 4. Protected: Visible to the package
and all subclasses.

13 | 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 other name){
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 class
Monk.monk(“Father
and not to the object.
Shinodah"); // Accessing the
 A static method can be accessed static method monk() and field
directly by the class name and by class name itself.
doesn‟t need any object.
System.out.println(Monk.monkName
 i.e ClassName.methodName(args) ); //Accessing the static method
monk() by using Object's
 A static method cannot refer to "this"
reference.
or "super" keywords in anyway Monk shinoda = new
 Static methods are called without Monk();
creating an object of class. shinoda.monk(“is not
dead");
 They are referenced by the class
name itself or reference to the Object System.out.println(shinoda.monkN
of that class. ame); } }
//Output: Father Shinoda
 They are stored in Permanent is not dead
Generation space of heap (in Static
Static methods and Final Variables…
memory)
 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.
 E.g. public class Test {

14 | P a g e
public static void  The class whose properties are inherited
main(String args[]) { is known as superclass (base class,
final int i = 10; parent class).
i = 30; // Error because
i is final.}}  Therefore, a subclass is a specialized
Don‟t Confuse with Constants version of a superclass.

 The java final keyword can be used  It inherits all of the instance variables
in various context: and methods defined by the superclass
and add its own, unique elements.
1. final variable - A variable
declared as final prevents the  The extends keyword: is the keyword
content of that variable being used to inherit the properties of a class.
modified Below given is the syntax of extends
keyword.
2. final method - A method
declared as final prevents the  Sytax:
user from overriding that class Super{
method
.....}
3. final class - A class declared
as final cannot be extended class Sub extends Super{ }
thus prevents inheritance

Chapter – Three: Inheritance


and Polymorphism class Calculation{
What is Inheritance? int z;
 Inheritance is one of the cornerstones of public void addition(int x,
object-oriented programming because it int y){
z=x+y;
allows the creation of hierarchical
System.out.println("The
classifications.
sum of the given numbers:"+z);
 Inheritance is the process where one }
class acquires the properties (methods public void Substraction(int
and fields) of another. x,int y){
z=x-y;
 A class that is inherited is called a System.out.println("The
superclass. difference between the given
numbers:"+z);
 The class that does the inheriting is } }
called a subclass.
 OR: The class which inherits the public class My_Calculation
properties of other is known as subclass extends Calculation{
(derived class, child class) and
public void
multiplication(int x, int y){

15 | P a g e
z=x*y; System.out.println("Contents of
System.out.println("The subOb: ");
product of the given subOb.showij(); subOb.showk();
numbers:"+z); System.out.println();
} System.out.println("Sum of i, j
public static void and k in subOb:");
main(String args[]){ subOb.sum(); }}
int a=20, b=10;
My_Calculation demo = new
My_Calculation(); Types of inheritance
demo.addition(a, b); 1. Simple/single inheritance: is damn easy
demo.Substraction(a, b); to understand. When a class extends
demo.multiplication(a, b); another one class only.
2. Multi-Level inheritance: One can
}}
inherit from a derived class, thereby
making this derived class the base class
Example 2 for the new class.
class A { 3. Hierarchical inheritance: One class is
int i, j; inherited by many sub classes.
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[]) {  Java does not support the
A superOb = new A(); inheritance of multiple super classes
B subOb = new B();
into a single subclass. (Multiple &
superOb.i = 10;
Hybrid inheritances)
superOb.j = 20;
System.out.println("Contents of  No class can be a superclass of itself
superOb: ");
superOb.showij();  Superclass can be used by itself.
/* The subclass has access to  The superclass has no knowledge of
all public members of its
what a subclass adds to it.
superclass. */
subOb.i = 7; subOb.j = 8;  Constructors are not members, so
subOb.k = 9; they are not inherited by subclasses.

16 | P a g e
 But the constructor of the superclass String barking(){
can be invoked from the subclass. }}
//main{
Member Access and Inheritance Animal wild=new Animal();
 Although a subclass includes all of Dog fries=new Dog();
the members of its superclass, it wild=fries;
cannot access those members of the Wild.show()// correct show() is
superclass that have been declared as defined in Animal
private. Wild.breed=“Woo woo”// ERROR
}
 For example:

The super keyword


class A {  Since encapsulation is a primary
int i; private int j; // private attribute of OOP, Whenever a subclass
to A needs to refer to its immediate
void setij(int x, int y) { superclass, it can do so by use of the
i = x; keyword super.
j = y;
}}  Super has two general forms.
// A's j is not accessible here. 1. Used to access parent class
class B extends A { instance members.
int total;
void sum() { 2. Used to access parent class
total = i + j; // ERROR, j is constructor.
not accessible here
}} 1. Used to access parent class
class Access { instance members.
public static void main(String  super acts somewhat like this, except
args[]) { that it always refers to the superclass of
B subOb = new B(); the subclass in which it is used.
subOb.setij(10, 12);
subOb.sum();  Super has the form: super.member Here,
System.out.println("Total is " + member can be either a method or an
subOb.total); instance variable.
}}
 Super is most applicable to resolve
member hiding.
A Superclass Variable Can Reference a
 super( ) must always be the first
Subclass Object
statement executed inside a subclass‟
class Animal{ constructor.
string name; int age
int show(){…}}  Consider the next simple class
class Dog extends Animal{
String breed;

17 | P a g e
1.1.Used to access parent class // Using super to overcome name
instance members-Variable. hiding.
class A {
int i; }
class B extends A {
int i; // this i hides the i in
A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B }
void show() {
System.out.println("i in
superclass: " + super.i);
System.out.println("i in
subclass: " + i);
}}
class UseSuper {
public static void main(String
Output: args[]) {
black
B subOb = new B(1, 2);
white
subOb.show();
1.2.Used to access parent class }}
instance members-Method.

2. Used to access parent class


constructor.
 A subclass can call a constructor
defined by its superclass by use of
the following form of super:
super(arg-list);
 Here, arg-list specifies any
arguments needed by the constructor
in the superclass.
 super( ) must always be the first
statement executed inside a subclass‟
constructor.
Here super is used to resolve overridden
methods.
Output:
eating …
barking...

18 | 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: } }
animal is created When Constructors Are Called?
dog is created
If you need more: Search on  In a class hierarchy, constructors
https://www.javatpoint.com/super-keyword are called in order of derivation,
from superclass to subclass.
Creating a Multi-level Hierarchy
 Further, since super( ) must be the
first statement executed in a
class SuperClass3 subclass‟ constructor, this order is
{ the same whether or not super( ) is
public void display3() used.
{
 If super( ) is not used, then the
System.out.println("This is default or parameter less constructor
display3 method"); of each superclass will be executed.
} } Why?
class SuperClass2 extends
// Demonstrate when constructors
SuperClass3
are called. Create a super
{
class.
public void display2()
class A {
{
A() {
System.out.println("Inside A's
System.out.println("This is
constructor.");
display2 method");
} }
} }
// Create a subclass by
class SuperClass1 extends
extending class A.
SuperClass2
class B extends A {
{
B() {
public void display1()
System.out.println("Inside B's
{
constructor.");

19 | 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 C's i + " " + j);
constructor."); }}
}} class B extends A {
class CallingCons { int k;
public static void main(String B(int a, int b, int c) {
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: " + k);
Inside A‟s Constructor }}
Inside A‟s Constructor class Override {
Inside A‟s Constructor public static void main(String
args[]) {
Method Overriding
B subOb = new B(1, 2, 3);
 In a class hierarchy, when a method in a subOb.show(); Which method is
subclass has the same name and type called? // this calls show() in
signature as a method in its superclass, B
then the method in the subclass is said to }}
override the method in the superclass. Output:
 When an overridden method is called K: 3
from within a subclass, it will always
refer to the version of that method class A {
int i, j;
defined by the subclass.
A(int a, int b) {
 The version of the method defined by i = a;
the superclass will be hidden. j = b; }
void show() {
 Method overriding occurs only when the System.out.println("i and j: " +
names and the type signatures of the two i + " " + j);
methods are identical. }}
class B extends A {
int k;
What is the output of the B(int a, int b, int c) {
following program? super(a, b);
// Method overriding. k = c; }
class A { void show() {
int i, j; super.show(); // this calls A's
A(int a, int b) { show()

20 | P a g e
System.out.println("k: " + k); class MyChildClass extends
}} MyBaseClass{
class Override { protected void disp(){
public static void main(String System.out.println("Child
args[]) { class method");
B subOb = new B(1, 2, 3); }
subOb.show(); Which one is public static void main(
called? // this calls show() in String args[]) {
B MyChildClass obj = new
}} MyChildClass();
obj.disp();
Output: }}
I and j: 1 2 Output:
K: 3 Exception in thread "main"
Rules of method overriding in Java.. java.lang.Error: Unresolved
 Argument list: The argument list of compilation
overriding (method of subclass) and problem: Cannot reduce the
Overridden (method of super class) visibility of the inherited
method from MyBaseClass
method must be similar.
 The data types of the arguments and
// The following program can run
their sequence should exactly match.
very well. But what is the
 Method names: must be similar. output?
class MyBaseClass{
 private, static and final methods cannot protected void disp()
be overridden as they are local to the {
class.
System.out.println("Parent class
 Access Modifier of the overriding
method");
method cannot be more restrictive than
}}
the overridden method of parent class. class MyChildClass extends
 For example look the following MyBaseClass{
Program. public void disp(){
System.out.println("Child
class method");
}
// The following program cannot public static void main(
be run well. String args[]) {
class MyBaseClass{ MyChildClass obj = new
public void disp() MyChildClass();
{ obj.disp();
}}
System.out.println("Parent class Output:
method"); Child class method
}}

21 | 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 parent runtime, because during method call
class method based on its requirement. which method(parent class or child
class) is to be executed is determined by
 The class can give its own specific the type of object.
implementation to an inherited method
without even modifying the parent class  This process in which call to the
code. overridden method is resolved at runtime
is known as dynamic method dispatch.
 This is helpful when a class has several
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
class ABC{
without touching the parent class code.
//Overridden method
 Method overriding is used for runtime public void disp()
polymorphism {
System.out.println("disp()
Method Overriding method of parent class");
}}
class Demo extends ABC{
Dynamic Method Dispatch //Overriding method
 Dynamic method dispatch is the public void disp(){
mechanism by which a call to an System.out.println("disp()
overridden method is resolved at run method of Child class");
time, rather than compile time. }
public void newMethod(){
 Dynamic method dispatch is important System.out.println("new
because this is how Java implements method of child class");
run-time polymorphism }
public static void main(
 When an overridden method is called
String args[]) {
through a superclass reference, Java
/* When Parent class
determines which version of that method
reference refers to the parent
to execute based upon the type of the class object then in this
object being referred to at the time the case overridden method (the
call occurs. method of parent class) is
 Thus, this determination is made at run called. */
time. ABC obj = new ABC();
obj.disp();
 Method Overriding is an example of
runtime polymorphism.

22 | P a g e
/* When parent class reference r.callme(); // calls A's version
refers to the child class object of callme
then the overriding method r = b; // r refers to a B object
(method of child class) is r.callme(); // calls B's version
called.This is called dynamic of callme
method dispatch and runtime r = c; // r refers to a C object
polymorphism*/ r.callme(); // calls C's version
ABC obj2 = new Demo(); of callme
obj2.disp(); }}
}} Output:
Inside A's callme method
Inside B's callme method
Example 2
Inside C's callme method
// Dynamic Method Dispatch. Abstract Classes
class A {  A classes declared with abstract
void callme() { keyword and can‟t be instantiated.
System.out.println("Inside A's
 Used to hide meaningless methods:
callme method");
}}  There can be no objects of an abstract
class B extends A { class. .:.
// override callme()
void callme() {  An abstract class cannot be directly
System.out.println("Inside B's instantiated with the new operator.
callme method");  You cannot declare abstract
}} constructors, or abstract static methods
class C extends A {
// override callme()  Syntax: abstract class class_name
void callme() {
System.out.println("Inside C's Example:
callme method"); abstract class A {
}} abstract void callme();
class Dispatch { // concrete methods are still
public static void main(String allowed in abstract classes
args[]) { void callmetoo() {
A a = new A(); // object of type System.out.println("This is a
A concrete method.");
B b = new B(); // object of type }}
B class B extends A {
C c = new C(); // object of type void callme() {
C System.out.println("B's
A r; // obtain a reference of implementation of callme.");
type A }}
r = a; // r refers to an A class AbstractDemo {
object public static void main(String
args[]) {

23 | P a g e
B b = new B(); Binding & final
b.callme();  Binding of overridden methods happen
b.callmetoo(); at runtime which is known as dynamic
A ob=new A()// ERROR }} binding.
Using final with Inheritance
 The compiler is free to inline calls to
 The keyword final has three uses.
them because it “knows” they will not be
1. To create the equivalent of a overridden by a subclass.
named constant (final variable)
 Normally, Java resolves calls to methods
- A variable declared as final
dynamically, at run time called late
prevents the content of that
binding.
variable being modified.
 However, since final methods cannot be
2. To Prevent Overriding in
overridden, a call to one can be resolved
Methods (final method) - A
at compile time called early binding.
method declared as final cannot
be overridden.  Static Binding:
E.g.  Dynamic Binding:
class A {
final void meth() {  Multi-threaded program contains two
System.out.println("This or more parts that can run concurrently.
is a final method.");  Each part can handle different task at the
}} same time making optimal use of the
class B extends A {
available resources. Especially, when
void meth() { // ERROR!
your computer has multiple CPUs.
Can't override.
System.out.println("Ille Summery:
gal!");
}} Abstract:
3. To Prevent Inheritance in Classes
 Classes: declared with abstract
(final class) - A class declared as
keyword and can‟t be instantiated.
final cannot be extended thus
prevents inheritance. It is illegal  Methods: without body (no
to declare a class as both abstract implementation)
and final. E.g.
Final:
final class A {
 Class: declared as final prevents
// ...}
inheritance.
// The following class is
illegal.  Method: declared as final prevents
class B extends A { // overriding that method.
ERROR! Can’t has subclass A
// ...}  Variable: declared as final prevents
the content modification.

24 | P a g e
Static:  It is one of the basic principles of object
oriented programming.
 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 Types of Polymorphism
polymorphism refers to a principle in  There are 2 basic types of
biology in which an organism or species polymorphism:
can have many different forms or stages.
1. Static Polymorphism
 This principle can also be applied to
2. Dynamic Polymorphism.
object-oriented programming like the
Java language  Some programmers classify
polymorphism in to three:
 Polymorphism is the ability of an object
to take on many forms. 1. Ad-hoc (overloading and
overriding),
 The most common use of polymorphism
in OOP occurs when a parent class 2. Parametric (generics) and
reference is used to refer to a child class
3. Dynamic method binding.
object.
 Any Java object that can pass more than 1. Static polymorphism
one IS-A test is considered to be  Static Polymorphism is in other words
termed as compile-time binding or early
polymorphic.
binding.
 In Java, all Java objects are polymorphic
since any object will pass the IS-A test  Static binding occurs at compile time.
for their own type and for the class  Method overloading is a case of static
Object. binding and in this case binding of
 Polymorphism is derived from 2 Greek method call to its definition happens at
words: poly and morphs. the time of compilation.

 The word "poly" means many and 2. Dynamic polymorphism


"morphs" means forms. So  Dynamic (or late) method binding is the
polymorphism means many forms. ability of a program to resolve references
to subclass methods at runtime.
 polymorphism is the capability of an
action or method to do different things  For example assume that three
based on the object that it is acting upon. subclasses (Cow, Dog and Snake) have
been created based on the Animal

25 | P a g e
abstract class, each having their own Test t= new Test();
speak() method. System.out.println(t
instanceof Test);
 Although each method reference is to an }}
Animal (but no animal objects exist), the Output: True
program is will resolve the correct
The instance of operator-Down
method reference at runtime.
Casting

public class AnimalReference


{
public static void main(String
args[])
Animal ref ; //
set up var for an Animal
Cow aCow = new Cow("Bossy");
// makes specific objects
Dog aDog = new Dog("Rover"); E.g. of downcasting with instanceof
Snake aSnake = new operator
Snake("Ernie");
// now reference each as an class Parent{ }
Animal public class Child extends
ref = aCow; ref.speak(); Parent{
ref = aDog; ref.speak(); public void check(){
ref = aSnake; ref.speak();
} System.out.println("Sucessfull
The instance of operator Casting");
 In Java, instanceof operator is used to }
check the type of an object at runtime. public static void
 It is the means by which your program show(Parent p){
can obtain run-time type information if(p instanceof
about an object. Child){
Child
 instanceof operator is also important in b1=(Child)p;
case of casting object at runtime. b1.check();
 instanceof operator return boolean value, }}
if an object reference is of specified type public static void
then it return true otherwise false. main(String[] args){
Parent p=new Child();
public class Test Child.show(p);
{ }} Output: Sucessfull
public static void Casting
main(String[] args)
{

26 | 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 a
polymorphism in terms of Inheritance, subclass of Throwable.
method overloading and method
 Exceptions occur for various reasons.
overriding.
E.g.
 Method overriding allows Java to invoke
 A user has entered invalid data.
method based on a particular object at
run-time instead of declared type while  A file that needs to be opened cannot be
coding. found.

Where to use polymorphism in code?  A network connection has been lost in


1. Method argument: the middle of communications or the
2. Variable names: 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
 Physical resources that have failed in
a general statement or does not follow a
some manner.
rule.”
 An exception is an event, which occurs import java.util.Scanner;
import java.util.*;
during the execution of a program, that
public class ExceptionDemo {
disrupts the normal flow of the
public static void
program's instructions. main(String args[])
 An exception is an indication of a {
problem that occurs during a program‟s Scanner reader=new
execution. Scanner (System. in);

 An exception is a runtime error. System.out.println("Enter a


number :");
 A Java exception is an instance of a class int num=
derived from Throwable. reader.nextInt(); // try to
 The Throwable class is contained in the enter your name
java.lang package, and subclasses of
Throwable are contained in various System.out.println("The number
is :" + num); } }
packages.
Stack trace: an Information about an
 Errors related to GUI components are exception
included in the java.awt package;
numeric exceptions are included in the Catching Exception…
java.lang package because they are import java.util.Scanner;
related to the java.lang.Number class. import java.util.*;
public class ExceptionDemo {

27 | 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 java.io.FileReader;
int num= public class FilenotFound_Demo {
reader.nextInt(); public static void
main(String args[]){
System.out.println("The number File file=new
is :" + num); File("E://file.txt");
} FileReader fr = new
catch FileReader(file);
(InputMismatchException e){ }}
 If you try to compile the
System.out.println("There is above program you will get
type mis match :"); exceptions like this.
} C:\>javac FilenotFound_Demo.java
finally{ FilenotFound_Demo.java:8: error:
unreported exception
System.out.println("This part is FileNotFoundException; must be
always done"); caught or declared to be thrown
}} } FileReader fr = new
Exception Types FileReader(file);
1 error
 There two categories of Exceptions:
 Unchecked exceptions: Is an
1. Checked exception: Is an exception that occurs at the time of
exception that occurs at the compile execution, these are also called as
time, Runtime Exceptions.

 These are also called as compile  These include programming bugs,


time exceptions. such as logic errors or improper use
of an API.
 These exceptions cannot simply
be ignored at the time of  Runtime exceptions are ignored at
compilation, the time of compilation.

 The Programmer should take  For example, if you have declared an


care of (handle) these exceptions. array of size 5 in your program, and
trying to call the 6th element of the
 For example, if you use array then an
FileReader class in your program ArrayIndexOutOfBoundsExceptione
to read data from a file, if the file xception occurs.
specified in its constructor
2. Other: Errors

28 | P a g e
Exception Vs Errors  A stream is linked to a physical device
1. Errors: An Error indicates by the Java I/O system.
serious problem that a  Java implements streams within class
reasonable application should hierarchies defined in the java.io
not try to catch. package.
2. Exception: Exception  there are two kinds of Streams
indicates conditions that a
reasonable application might  InPutStream: The InputStream is used
try to catch. 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
 Java byte streams are used to
errors
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 files.
Catch(ExceptionType2 exOb ) {
//handler for ExceptionType2  The most frequently used classes are
} , FileInputStream and
FileOutputStream.
File and Stream import java.io.*;
 A file is an object on a computer that public class CopyFile {
stores data, information, settings, or public static void
commands used with a computer main(String args[]) throws
program. IOException
{
 E.g. Image, text, video, FileInputStream in = null;
audio…(Multimedia) FileOutputStream out =
null;
 In a graphical user interface (GUI) such
try {
as Microsoft Windows, files display as in = new
icons that relate to the program that FileInputStream("C:\\Users\\FIKR
opens the file. TE\\Documents\\text.txt");
 A stream is an abstraction that either out = new
FileOutputStream("C:\\Users\\FIK
produces or consumes information.
RTE\\Documents\\textCopied.txt")
 A stream is a communication channel ;
that a program has with the outside int c;
world. It is used to transfer data items in while ((c = in.read())
succession. != -1) {

29 | P a g e
out.write(c); }  The InputStream is used to read data
}finally { from a source and the OutputStream
if (in != null) { is used for writing data to a
in.close(); } destination.
if (out != null) {
out.close(); } }}} Chapter – Five: Java Interface
2. Character Streams:
 An interface in java is a blueprint of
 Java Character streams are used to a class.
perform input and output for 16-bit
 It has static constants and abstract
unicode.
methods.
 Character stream is useful when we
 The interface in java is a mechanism
want to process text files.
to achieve abstraction.
 These text files can be processed
 There can be only abstract methods
character by character.
in the java interface not method body
 The most frequently used classes are (contain only signature, not body).
, FileReader and FileWriter.
 It is used to achieve abstraction and
import java.io.*; multiple inheritance in Java.
public class CopyFile {
 Java Interface also represents IS-A
public static void
relationship.
main(String args[]) throws
IOException  It cannot be instantiated just like
{ abstract class.
FileReader in = null;
FileWriter out = null;  There are mainly three reasons to use
try { interface.
in = new
 It is used to achieve
FileReader("input.txt");
out = new abstraction.
FileWriter("output.txt");  By interface, we can support
int c; the functionality of multiple
while ((c = in.read()) inheritance.
!= -1) {
out.write(c); }  It can be used to achieve
}finally { loose coupling.
if (in != null) {
in.close(); }  Interface is declared by using
if (out != null) { interface keyword.
out.close(); Syntax:
} } }}
 Reading and Writing Files: As interface <interface_name>{
described earlier, A stream can be
defined as a sequence of data.

30 | 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 them
// declare constant fields // declare methods as: public abstract void
that abstract // by default. 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 public, implement both the abstract
static and final by default. methods else you will get
compilation error */
 A class that implement interface public void method1(){
must implement all the methods System.out.println("imple
declared in the interface. mentation of method1");
 If a class implements an interface }
public void method2(){
and does not provide method bodies
System.out.println("imple
for all functions specified in the
mentation of method2");
interface, then class must be declared
}
abstract. public static void
Rules of Interface main(String arg[]){
MyInterface obj = new
 Variables declared in an interface are
Demo();
public, static & final by default.
obj.method1();}}
 Java does not allow you to extend Output:implementation of method1
more than one class, However you
Extending Interface
can implement more than one
 It is called Interface inheritance
interfaces in your class.
interface Printable{
 class implements interface but an
void print(); }
interface extends another interfaces.
interface Showable extends
Implementing Interface…E.g. Printable{
void show(); }
interface MyInterface class TestInterface4 implements
{ Showable{
/* All the methods are public public void
abstract by default print(){System.out.println("Hell
* As you see they have no o");}
body

31 | P a g e
public void public void
show(){System.out.println("Welco doSomething();
me");} }
public static void main(String public interface InterfaceC
args[]){ extends InterfaceA, InterfaceB {
TestInterface4 obj = new //same method is declared in
TestInterface4(); both InterfaceA and InterfaceB
obj.print(); public void
obj.show(); doSomething();
}} }
Extending multiple Interface
Multiple inheritance in Java by E.g.
interface
public interface InterfaceA {
 If a class implements multiple
public void
interfaces, or an interface extends doSomething();
multiple interfaces i.e. known as }
multiple inheritance. public interface InterfaceB {
public void
doSomething();
}
public interface InterfaceC
extends InterfaceA, InterfaceB {
//same method is declared in
both InterfaceA and InterfaceB
public void
doSomething();
}

Implementing multiple interface


interface Printable{
void print();
}
interface Showable{
Extending multiple Interface
void show();
 A single interface can extend }
multiple interfaces, below is a simple class A7 implements Printable,Sh
example. owable{
public void print(){System.out.p
public interface InterfaceA { rintln("Hello");}
public void public void show(){System.out.pr
doSomething(); intln("Welcome");}
} public static void main(String a
public interface InterfaceB { rgs[]){
A7 obj = new A7();

32 | P a g e
obj.print(); Chapter – Six: GUI in JDBC
obj.show();
} }
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.

33 | P a g e
34 | P a g e

You might also like