Object Oriented Programming in Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

DEBRE BERHAN UNIVERSITY

College of Computing
Department of Information
Systems
Short not manual for Exit exam (Module)

Object Oriented Programming with Java

By: College of Computing Exam Committee teem

Debre Berhan University, Debre Berhan, Ethiopia

January, 2023
Course Title Object Oriented Programming with Java
Module Title Advanced Programming
Module Code ITec-M2051 Course Code: ITech2052
CP/ECTS 7
Study Hours Lecture: - 32 Laboratory: Tutorial: - Home Study: 71 Total:135
48 32
Prerequisite(s): Fundamentals of Programming II Course Code: ITec2042
Course This course will cover almost all lab practice of Object Oriented
Description Programming with Java using NetBeans 8.0, the concept of class and
object, inheritance, abstraction, polymorphism and exception handling....
will be discussed widely.
Learning At the end of this course, Students will be able to:
Outcomes • Understand the concept of Object Oriented Programming
• Differentiate class and object
• Understand Exception Handling mechanism
• Do Simple Project
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
and interfaces together into what is
E.g. java, C++, C#, VB6, Python…
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
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
bytecodes.  usually having a linear order of
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
different platforms.  allow the programmer to break
down the problem into objects:
Java is: + Object Oriented + Platform
Independent  Easy to debugging.
+ Simple + Secure  E.g. java, C++, C#, VB6, Python
+ Portable + 3. Declarative:
Multithreaded + Robust
 Describe a problem rather than
Q1: What is the d/c between compiler and defining a solution
interpreter?
 Describes what something is like,
 The Java platform is a bit different to rather than how to create it.
other platforms, in that it consists of
software only – that means it is ፩. Objects: (Recall)
hardware-independent.  Are instances of a class
 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
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
extends, implements, for… 0x09), (\t)
 Identifiers: programmers c. The line separators
given name; grade, gRade… characters newline(\n) (hex
 Literals (Constants values): 0x0a)
55, 60.78, “Hi”, ‘M’… Java d. The carriage return (hex
language specifies five major 0x0d) characters(\r)
types of literals => integer,
floating, character, string & e. The form feed character (hex
Boolean literals 0x0c), (\f) : produce 
 Operators: Are symbols that 1.3. Variables in Java
take one or more arguments Variable = Data Type + Identifier
(operands) and operates on
them to produce a result. An There are three kinds of variables in Java:
operator performs a function A. Local variables:
on one (Unary), two (Binary),
or three operands (Ternary).  Local variables are declared in
Java has one ternary operator, methods, constructors, or blocks.
?:, which is a short-hand if-  has only local scope
else statement. E.g. c=x?w:s;
Operators can be Arithmetic,  Access modifiers cannot be used
Logical, assignment, for local variables.
Relational, conditional,  They are visible only within the
Increment, declared method, constructor, or
 Separators: symbols used to block.
indicate where groups of  Have not a default value
codes are divided and
arranged. E.g. () , {}, [] , ; , , ,  Should be declared and
. initialized @ z first time.
 Declare before use anywhere in a E.g. class MyClass
method or block. { float aFloat; }
 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  Destination is wider
how much space it occupies in than the source
storage and how the bit pattern
Widening conversion usually
stored is 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,
char & Boolean)
long l=560; float f =
2. Reference types: Arrays, classes,
and interfaces, String) l; //no explicit type
casting required
 Note: Boolean type has a value true or
false (there is no conversion b/n Boolean 2. Narrowing (Explicit)
and other types). Casting: if you want to
narrow or go in the other
 All non-primitive types are reference direction, Java won’t do that
types, so all class types are reference automatically. You have to
types. 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 Syntax: smallerDT
variable of another type is known as var=(smallerDT)largerDTVar
Type Casting. OR largerValue;
 In Java, type casting is classified into Example: float y=78.9f; byte
two types b = (byte)y; //explicit type
casting required
1. Widening, (Implicit) or
Automatic Casting: Java int x = (int)2.7; double d =
supports automatic widening, 100.04; long l = (long)d;
a kind of conversion from Question: What is the merit
one type to another which and demerit of implicit and
doesn’t lose information. explicit type casting?
Boxing and Unboxing:
 Autoboxing is the automatic
conversion that the Java compiler
makes between the primitive types
Two conditions for automatic and their corresponding object
casting wrapper classes.
 Types are compatible
 For example, converting an int to an 3. Control flow statements: regulates
Integer, a double to a Double, and so the order of statements execution
on.
Selection: the if() and switch()
 If the conversion goes the other way, statements
this is called unboxing.
Iteration: The for(), while() and
 Converting primitive data types into do…while() statements
object is called boxing.
4. Jumping Statements: to jump out
 Therefore, while using a wrapper of loops and to control other areas of
class you just need to pass the value program java uses break and
of the primitive data type to the continue statements.
constructor of the Wrapper class. The break statement: used to exit a
loop
 And the Wrapper object will be
The Continue Statement: used to
converted back to a primitive data
force program to go back to the top
type, called unboxing.
of a loop
 The Number class is part of the Labels: Java does not include a goto
java.lang package. statement.
Instead of goto, Java allows you to
Overview of Java statements combine break and continue with a
 Statements are roughly equivalent to label.
sentences in natural languages.
 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;
Chapter Two: Classes and  Thus, the data for one object is
separate and unique from the data for
Objects another.
2.1. Fundamentals of Classes
 All methods have the same general
 A class is a blue print from which
form as main( )
individual objects are created.
 However, most methods will not be
 Class is a template for an object, and
specified as static or public.
an object is an instance of a class
 Java classes do not need to have a
 Class is the logical construct upon
main( ) method except the starting
which the entire Java language is
point for your program.
built because it defines the shape and
nature of an object.  Further, applets don’t require a main(
) method at all.
 As such, the class forms the basis for
object-oriented programming in  A class defines a new type of data (it
Java. is a reference type).
 Classes usually consist of two things:  In this case, the new data type is
instance variables and methods called Dog.
 Any concept you wish to implement  You will use this name to declare
in a Java program must be objects of type Dog.
encapsulated within a class.
 a class declaration only creates a
 A sample of a class is given below: template; it does not create an actual
object.
 To actually create a Dog object, use
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
 The code is contained within Dog.
methods (The operation is done
 Thus, it will have “physical”
inside)
reality .

2.2. Types of classes


ሀ. The Common types of classes:
1. Wrapper Class:- The eight ሐ. According to Inheritance: Classes are
classes of java.lang package classified in to 2:
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.
 If import statements are present then class Dog {
they must be written between the int age; String breed, color; }
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 +
“Dog‘s age:” + myDog.age + “Color: ” +
 It is not possible to declare different
myDog.color;
import and/or package statements to 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
 Dog myDog = new Dog();
instance variable.
OR
 For example, to assign the age
 Dog myDog; // declare
variable of myDog the value 10, you
reference/template to object
would use the following statement:
 myDog = new Dog(); //
myDog.age = 10; //This is called
allocate a Dog object
instantiating a class.
Methods
 This statement tells the compiler to
 Are members of classes and do
assign the copy of age that is
operations.
contained within the myDog object
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 System.out.println("double a: "
type is not void + a);
} return a*a; } }
Read About class Overload {
Methods…Returning a Value public static void main(String
args[]) {
Methods…Adding a method that takes OverloadDemo ob = new
parameters OverloadDemo();
Method Overloading double result; // call all
versions of test()
 Is a process of having the same name
ob.test(); ob.test(10);
for different methods as long as their
ob.test(10, 20);
parameter list or data types in the result = ob.test(123.25);
parameter list is different? System.out.println("Result of
 The return type alone is insufficient ob.test(123.25): " + result); }
to distinguish two versions of a }
method.
 Parameters are key identifiers of Method Overriding
OM. In a class hierarchy, when a method in a
subclass has the same name and type
 Is one of the ways that Java supports signature as a method in its superclass, this
polymorphism is called method Overriding.
 the method in the subclass is said to
 Java’s automatic type conversions override the method in the
can play a role in overload superclass.
resolution.  The Method in the super class is
known as an overridden method
 Exammple: // Demonstrate method
which is called within a subclass.
overloading.  The version of the method defined
class OverloadDemo { by the superclass will be hidden.
void test() {  E.g. :
System.out.println("No
parameters"); } // Method overriding
void test(int a) { // Overload class A {
test for one integer parameter. int i ,j;
System.out.println("a: " + a); } A ( int a, int b) {
void test(int a, int b) { // i= a;
Overload test for two integer j= b;
parameters. }
System.out.println("a and b: " + // display i and j
a + " " + b); } void show ( ) {
double test(double a) { // Sytem.out.println ( “ i and j :
overload test for a double “ + i
parameter + “ “ + j );
}
}  Once you define your own
class B extends A { constructor, the default constructor is
int k; no longer used.
B ( int a, int b, int c) {
super( a, b);  Syntax:
k= c;  Have the same name with their class
}
name.
// display k – this overrides
show( ) in A  Have not return type, not even void.
void show ( ) {
System.out.println ( “ k : “ + k  With curly brasses
);  Constructor example: page 22(Lab
} Manual)
}
class override {  Parameterized Constructors:
public static void main ( String similar with parameterized methods.
args[ ] ) { Refer your lab manual..
B subob = new B ( 1, 2, 3);
subob.show( ) ; // this calls  Overloading Constructors:
show( ) in B; Reding Assignment
}
}  The this Keyword:
The output produced by this
program is shown here :  Instance Variable Hiding:
k : 3  Garbage Collection:
Constructors
 Performs automatic initialization of  The finalize( ) Method:
objects. .:.  Overloading Constructors:
 Initializes an object immediately  Returning Objects:
upon creation.
 Recursion:
 Once defined, the constructor is
automatically called immediately  Introducing Nested and Inner
after the object is created, before the Classes:
new operator completes. Garbage Collection
 The default constructor  The ability of deallocation of
automatically initializes all instance memory automatically.
variables to zero and all object
references to NULL.  When no references to an object
exist, that object is assumed to be no
 The default constructor is often longer needed, and the memory
sufficient for simple classes, but it occupied by the object can be
usually won’t do for more reclaimed.
sophisticated ones.
 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
recursion. all of the variables and
// 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;
return result; } } Access level modifiers determine whether
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.
 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 {
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,
int y){
object-oriented programming because it
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){
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();
superOb.i = 10; into a single subclass. (Multiple &
superOb.j = 20; Hybrid inheritances)
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
all public members of its  The superclass has no knowledge of
superclass. */ what a subclass adds to it.
subOb.i = 7; subOb.j = 8;  Constructors are not members, so
subOb.k = 9; they are not inherited by subclasses.
 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;
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...
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
SuperClass3 // Demonstrate when constructors
{ are called. Create a super
public void display2() class.
{ class A {
A() {
System.out.println("This is System.out.println("Inside A's
display2 method"); constructor.");
} } } }
class SuperClass1 extends // Create a subclass by
SuperClass2 extending class A.
{ class B extends A {
public void display1() B() {
{ System.out.println("Inside B's
constructor.");
}} 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:
K: 3
 When an overridden method is called
from within a subclass, it will always
class A {
refer to the version of that method
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()
System.out.println("k: " + class MyChildClass extends
k); }} 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
called? // this calls show() in main( 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
visibility of the inherited
Overridden (method of super class)
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
be run well. main( String args[]) {
class MyBaseClass{ MyChildClass obj = new
public void disp() MyChildClass();
{ obj.disp();
}}
System.out.println("Parent class Output:
method"); Child class method
}}
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
 When an overridden method is called
main( 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
called. */
 Thus, this determination is made at run
ABC obj = new ABC();
time.
obj.disp();
 Method Overriding is an example of
runtime polymorphism.
/* 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[]) {
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!
Can't override. your computer has multiple CPUs.
System.out.println("Ille Summery:
gal!");
}} Abstract:
3. To Prevent Inheritance in
 Classes: declared with abstract
Classes (final class) - A class
keyword and can’t be instantiated.
declared as final cannot be
extended thus prevents  Methods: without body (no
inheritance. It is illegal to declare implementation)
a class as both abstract and final.
Final:
E.g.
 Class: declared as final prevents
final class A {
// ...} inheritance.
// The following class is  Method: declared as final prevents
illegal. overriding that method.
class B extends A { //
ERROR! Can’t has subclass A  Variable: declared as final prevents
// ...} the content modification.
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
object. 3. Dynamic method binding.

 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
polymorphic. termed as compile-time binding or early
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
abstract class, each having their own {
speak() method. Test t= new Test();
System.out.println(t
 Although each method reference is to an instanceof Test);
Animal (but no animal objects exist), the }}
program is will resolve the correct Output: True
method reference at runtime. The instance of operator-Down
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
show(Parent p){
 It is the means by which your program
if(p instanceof
can obtain run-time type information
Child){
about an object.
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)
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.”
import java.util.Scanner;
 An exception is an event, which occurs
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
System.out.println("The number
Throwable are contained in various
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…
import java.util.Scanner;
java.lang package because they are
import java.util.*;
related to the java.lang.Number class.
public class ExceptionDemo {
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
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
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 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, audio… FileInputStream in = null;
(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\\
opens the file. FIKRTE\\Documents\\text.txt");
 A stream is an abstraction that either out = new
FileOutputStream("C:\\Users\\
produces or consumes information.
FIKRTE\\Documents\\
 A stream is a communication channel textCopied.txt");
that a program has with the outside int c;
world. It is used to transfer data items in while ((c =
succession. in.read()) != -1) {
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 (contain only signature, not body).
are , FileReader and FileWriter.
 It is used to achieve abstraction and
import java.io.*; multiple inheritance in Java.
public class CopyFile {
public static void  Java Interface also represents IS-A
main(String args[]) throws relationship.
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
FileReader("input.txt");  It is used to achieve
out = new abstraction.
FileWriter("output.txt");  By interface, we can support
int c; the functionality of multiple
while ((c =
inheritance.
in.read()) != -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.
// 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
declared in the interface. System.out.println("implementati
on of method1");
 If a class implements an interface
}
and does not provide method bodies
public void method2(){
for all functions specified in the
interface, then class must be declared System.out.println("implementati
abstract. on of method2");
}
Rules of Interface public static void
 Variables declared in an interface are main(String arg[]){
public, static & final by default. MyInterface obj = new
 Java does not allow you to extend Demo();
more than one class, However you obj.method1();}}
Output:implementation of method1
can implement more than one
interfaces in your class. Extending Interface
 class implements interface but an  It is called Interface inheritance
interface extends another interfaces. interface Printable{
Implementing Interface…E.g. void print(); }
interface Showable extends
interface MyInterface Printable{
{ void show(); }
/* All the methods are public class TestInterface4 implements
abstract by default Showable{
* As you see they have no public void print()
body {System.out.println("Hello");}
public void show() }
{System.out.println("Welcome");} public interface InterfaceC
public static void main(String extends InterfaceA, InterfaceB {
args[]){ //same method is declared in
TestInterface4 obj = new both InterfaceA and InterfaceB
TestInterface4(); public void
obj.print(); doSomething();
obj.show(); }
}}
Extending multiple Interface E.g.
Multiple inheritance in Java by
public interface InterfaceA {
interface
public void
 If a class implements multiple
doSomething();
interfaces, or an interface extends }
multiple interfaces i.e. known as public interface InterfaceB {
multiple inheritance. 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{
void show();
Extending multiple Interface
}
 A single interface can extend class A7 implements Printable,Sh
multiple interfaces, below is a simple owable{
example. public void print()
{System.out.println("Hello");}
public interface InterfaceA { public void show()
public void {System.out.println("Welcome");}
doSomething();
} public static void main(String a
public interface InterfaceB { rgs[]){
public void A7 obj = new A7();
doSomething(); 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.

You might also like