Sie sind auf Seite 1von 16

Mr.

Muhammad Shafiq Gondal Modern Programming Languages (CS-432)

Abstraction & Exception Handling


Week 6
Note:
It is intimated that following Lectures will not be repeated and would be
part of mid-term & final exam as well.

Objectives: Following lecture cover concept of abstraction, abstract class, abstract functions, key points of
abstract class and an example with ambiguity and its solution using abstraction. Search
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations) providing access protection and namespace management. This lecture covers
definition of exception, understanding of exception using example then hierarchy of exception
class and techniques to handle exception using try catch mechanism and explanation in detail.

Content: This lecture covers introduction of inheritance, types of inheritance, benefits of inheritance,
method overriding concept and demonstration of key word ‘super’.
.

Methods: Following lecture cover concept of abstraction, abstract class, abstract functions, key points of
abstract class and an example with ambiguity and its solution using abstraction. Search
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations) providing access protection and namespace management. This lecture covers
definition of exception, understanding of exception using example then hierarchy of exception
class and techniques to handle exception using try catch mechanism and explanation in detail.

Resources: Besides the lecture handout, this lesson will draw from the following Text books: Java - The
Complete Reference, 9th Edition - Herbert Schildt;

Evaluation: In this lecture I will evaluate them by drawing an example on the board and ask them one by
one to write possible output.

Assignment: Give them a home assignment on class diagram.

Lecture
Contents of Lecture Strategy
(Remarks)

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. Another way, it shows only important things to the user
and hides the internal details for example sending sms, you just type the text and
send the message. You don't know the internal processing about the message
delivery.

Key points of abstract class


1. abstract keyword is used to create an abstract class in java.
2. Abstract class in java can’t be instantiated.
3. We can use abstract keyword to create an abstract method, an abstract
method doesn’t have body.
4. If a class have abstract methods, then the class should also be abstract using
abstract keyword, else it will not compile.
5. It’s not necessary to have abstract class to have abstract method.
6. If abstract class doesn’t have any method implementation, it’s better to use
interface because java doesn’t support multiple class inheritance.
7. The subclass of abstract class in java must implement all the abstract
methods unless the subclass is also an abstract class.
8. All the methods in an interface are implicitly abstract unless the interface
methods are static or default. Static methods and default methods in
interfaces are added in Java 8, for more details read Java 8 interface
changes.
9. Java Abstract class can implement interfaces without even providing the
implementation of interface methods.
10. Java Abstract class is used to provide common method implementation to all
the subclasses or to provide default implementation.
11. We can run abstract class in java like any other class if it has main() method.

// Using run-time polymorphism.


class Figure {
double dim1;
double dim2;

Figure(double a, double b) {
dim1 = a;
dim2 = b;
}

double area() {
System.out.println("Area for Figure is
undefined.");
return 0;
ZA/Lesson 12 -2- Modern Programming Language (CS-432)
}
}

class Rectangle extends Figure {


Rectangle(double a, double b) {
super(a, b);
}

// override area for rectangle


double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {


Triangle(double a, double b) {
super(a, b);
}

// override area for right triangle


double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
Output:
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
Area for Figure is undefined.
Area is 0.0
Above output highlighted is ambiguous that is corrected using abstract class.

// Using run-time polymorphism.


abstract class Figure {
ZA/Lesson 12 -3- Modern Programming Language (CS-432)
double dim1;
double dim2;

Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
//abstract method
abstract double area();
}

class Rectangle extends Figure {


Rectangle(double a, double b) {
super(a, b);
}

// override area for rectangle


double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {


Triangle(double a, double b) {
super(a, b);
}

// override area for right triangle


double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
public class FindAreas {
public static void main(String args[]) {

Rectangle r = new Rectangle(9, 5);


Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());

}
}

Packages are used in Java in order to prevent naming conflicts, to control access, to

ZA/Lesson 12 -4- Modern Programming Language (CS-432)


make searching/locating and usage of classes, interfaces, enumerations and
annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces,
enumerations and annotations) providing access protection and namespace
management.
Some of the existing packages in Java are
• java.lang − bundles the fundamental classes
• java.io − classes for input, output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces,
etc. It is a good practice to group related classes implemented by you so that a
programmer can easily determine that the classes, interfaces, enumerations, and
annotations are related.
Since the package creates a new namespace there won't be any name conflicts with
names in other packages. Using packages, it is easier to provide access control and
it is also easier to locate the related classes.
Creating a Package
While creating a package, you should choose a name for the package and include a
package statement along with that name at the top of every source file that contains
the classes, interfaces, enumerations, and annotation types that you want to include
in the package.
The package statement should be the first line in the source file. There can be only
one package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and
annotation types will be placed in the current default package.
Example
Let us look at an example that creates a package called EmployeesPackage. It is a
good practice to use names of packages with lower case letters to avoid any
conflicts with the names of classes and interfaces.
Following package example contains interface named Employee
package employeespackage;
import java.util.Scanner;
public class Employee {

int id,age;
float salary;

ZA/Lesson 12 -5- Modern Programming Language (CS-432)


Now a package/folder with the name employeesoackage will be created in the
current directory and these class files will be placed in it as shown below.

The import Keyword


If a class wants to use another class in the same package, the package name need
not be used. Classes in the same package find each other without any special syntax.
Example
Here, a class named Employee is added to the employeepackage package. When
this class will be required to use in any other package

Interfaces in Java
Like a class, an interface can have methods and variables, but the methods declared
in interface are by default abstract (only method signature, no body).
• Interfaces specify what a class must do and not how. It is the blueprint of the
class.
• An Interface is about capabilities like a Player may be an interface and any
class implementing Player must be able to (or must implement) move(). So,
it specifies a set of methods that the class has to implement.
• If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then class must be declared abstract.

ZA/Lesson 12 -6- Modern Programming Language (CS-432)


• A Java library example is, Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
Syntax:
interface <interface_name> {

// declare constant fields


// declare methods that abstract
// by default.
}

To declare an interface, use interface keyword. It is used to provide total


abstraction. That means all the methods in interface are declared with empty body
and are public and all fields are public, static and final by default. A class that
implement interface must implement all the methods declared in the interface. To
implement interface use implements keyword.
Why do we use interface?
• It is used to achieve total abstraction.
• Since java does not support multiple inheritance in case of class, but by
using interface it can achieve multiple inheritance.
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in
interface are final, public and static.
//A simple interface
interface Player{
final int id = 10;
int move();
}
Run on IDE
To implement an interface we use keyword:
implement

//Java program to demonstrate working of


//interface.
import java.io.*;

//A simple interface


interface in1
{
ZA/Lesson 12 -7- Modern Programming Language (CS-432)
// public, static and final
final int a = 10;

// public and abstract


void display();
}

//A class that implements interface.


class testClass implements in1
{
// Implementing the capabilities of
// interface.
public void display()
{
System.out.println("Geek");
}

// Driver Code
public static void main (String[] args)
{
testClass t = new testClass();
t.display();
System.out.println(a);
}
}
Output:
Geek
10

A real-world example:
Let’s consider the example of vehicles like bicycle, car, bike………, they have
common functionalities. So, we make an interface and put all these common
functionalities. And lets Bicylce, Bike, car ….etc implement all these functionalities
in their own class in their own way.
import java.io.*;

interface Vehicle {

// all are the abstract methods.


void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}

ZA/Lesson 12 -8- Modern Programming Language (CS-432)


class Bicycle implements Vehicle{

int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){

gear = newGear;
}

// to increase speed
@Override
public void speedUp(int increment){

speed = speed + increment;


}

// to decrease speed
@Override
public void applyBrakes(int decrement){

speed = speed - decrement;


}

public void printStates() {


System.out.println("speed: " + speed
+ " gear: " + gear);
}
}

class Bike implements Vehicle {

int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){

gear = newGear;
}

// to increase speed
@Override
ZA/Lesson 12 -9- Modern Programming Language (CS-432)
public void speedUp(int increment){

speed = speed + increment;


}

// to decrease speed
@Override
public void applyBrakes(int decrement){

speed = speed - decrement;


}

public void printStates() {


System.out.println("speed: " + speed
+ " gear: " + gear);
}

}
class GFG {

public static void main (String[] args) {

// creating an inatance of Bicycle


// doing some operations
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);

System.out.println("Bicycle present
state :");
bicycle.printStates();

// creating instance of bike.


Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);

System.out.println("Bike present state


:");
bike.printStates();
}
}
Output;
Bicycle present state :
ZA/Lesson 12 -10- Modern Programming Language (CS-432)
speed: 2 gear: 2
Bike present state :
speed: 1 gear: 1

New features added in interfaces in JDK 8


Prior to JDK 8, interface could not define implementation. We can now add default
implementation for interface methods. This default implementation has special use
and does not affect the intention behind interfaces.
Suppose we need to add a new function in an existing interface. Obviously the old
code will not work as the classes have not implemented those new functions. So
with the help of default implementation, we will give a default body for the newly
added functions. Then the old codes will still work.
//A class that implements interface.
class testClass implements in1
{
// Driver Code
public static void main (String[] args)
{
testClass t = new testClass();
t.display();
}
}
Output:
hello

Another feature that was added in JDK 8 is that we can now define static methods in
interfaces which can be called independently without an object. Note: these methods
are not inherited.
//An example to show that interfaces can
//have methods from JDK 1.8 onwards
interface in1
{
final int a = 10;
static void display()
{
System.out.println("hello");
}
}

//A class that implements interface.


class testClass implements in1
{
// Driver Code
ZA/Lesson 12 -11- Modern Programming Language (CS-432)
public static void main (String[] args)
{
in1.display();
}
}
Output:

hello

Exception-Handling Fundamentals
A Java exception is an object that describes an exceptional (that is, error) condition
that has occurred in a piece of code. When an exceptional condition arises, an object
representing that exception is created and thrown in the method that caused the
error. That method may choose to handle the exception itself or pass it on. Either
way, at some point, the exception is caught and processed. Exceptions can be
generated by the Java run-time system, or they can be manually generated by your
code. Exceptions thrown by Java relate to fundamental errors that violate the rules
of the Java language or the constraints of the Java execution environment. Manually
generated exceptions are typically used to report some error condition to the caller
of a method. Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally. Briefly, here is how they work. Program statements that
you want to monitor for exceptions are contained within a try block. If an exception
occurs within the try block, it is thrown. Your code can catch this exception (using
catch) and handle it in some rational manner. System-generated exceptions are
automatically thrown by the Java runtime system. To manually throw an exception,
use the keyword throw. Any exception that is thrown out of a method must be
specified as such by a throws clause. Any code that absolutely must be executed
after a try block completes is put in a finally block.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
} catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
} catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed after try block ends
ZA/Lesson 12 -12- Modern Programming Language (CS-432)
}
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception
class is a subclass of the Throwable class. Other than the exception class there is
another subclass called Error which is derived from the Throwable class.

Errors are abnormal conditions that happen in case of severe failures, these are not
handled by the Java programs. Errors are generated to indicate errors generated by
the runtime environment. Example: JVM is out of memory. Normally, programs
cannot recover from errors.

The Exception class has two main subclasses: IOException class and
RuntimeException Class.

public class Exc1 {


static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
public class Exc1 {
static void subroutine() {
int d = 0;

ZA/Lesson 12 -13- Modern Programming Language (CS-432)


try{
int a = 10 / d;
}catch(ArithmeticException ex){
System.out.println(ex.toString());
}
System.out.println("Statement after catch
block");
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
Output:
java.lang.ArithmeticException: / by zero
Statement after catch block

Multiple catch Clauses


In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses, each
catching a different type of exception. When an exception is thrown, each catch
statement is inspected in order, and the first one whose type matches that of the
exception is executed. After one catch statement executes, the others are bypassed,
and execution continues after the try / catch block. The following example traps two
different exception types:
class MultipleCatches {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " +
e);
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob:
" + e);
}
System.out.println("After try/catch blocks.");
}
}
Output:
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
finally
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear

ZA/Lesson 12 -14- Modern Programming Language (CS-432)


path that alters the normal flow through the method. Depending upon how the
method is coded, it is even possible for an exception to cause the method to return
prematurely. This could be a problem in some methods. For example, if a method
opens a file upon entry and closes it upon exit, then you will not want the code that
closes the file to be bypassed by the exception-handling mechanism. The finally
keyword is designed to address this contingency. finally creates a block of code that
will be executed after a try /catch block has completed and before the code
following the try/catch block. The finally block will execute whether or not an
exception is thrown. If an exception is thrown, the finally block will execute even if
no catch statement matches the exception. Any time a method is about to return to
the caller from inside a try/catch block, via an uncaught exception or an explicit
return statement, the finally clause is also executed just before the method returns.
This can be useful for closing file handles and freeing up any other resources that
might have been allocated at the beginning of a method with the intent of disposing
of them before returning. The finally clause is optional. However, each try
statement requires at least one catch or a finally clause.

ZA/Lesson 12 -15- Modern Programming Language (CS-432)


Assignment #7
Dear students read the given lectures carefully as per the course objectives mentioned on the top and
carryout the assignment as per following instructions

Make an abstract class “MyCal” with these functions


1. int sum(int, int)
2. int sub(int,int)
3. int mul(int,int)
4. int div(int, int)
Now make child class of MyCal with name “MyCalculater”
Test class will take input and choice from user and perfume calculating functionality.
1. Submission Date: Sunday 12-April-2020 at 11:59PM, This will also count as your Attendance
for this week.

2. Text file of Execute able code and hand writing code after scanning will be submitted through
email

ZA/Lesson 12 -16- Modern Programming Language (CS-432)

Das könnte Ihnen auch gefallen