object orinted programming with java · 2020. 11. 25. · •inheritance inheritance is the process...

112
OBJECT ORINTED PROGRAMMING WITH JAVA

Upload: others

Post on 02-Aug-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

OBJECT ORINTED PROGRAMMING WITH JAVA

Page 2: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Object Oriented Programming using Java

Module -1

Object oriented Programming Concepts

Page 3: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture -1

Procedure Oriented Programming Systems

Object Oriented Programming Systems

Comparison of Procedure Oriented and Object Oriented

Programming

Page 4: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture -1

Page 5: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Language with C

• Variables

• Operators

• new and delete operator

• Conditional statements

Lecture -2

Page 6: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Loops

• Arrays

• Structures

• Functions

Lecture -2

Page 7: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Classes with Syntax

A class is a blueprint for any functional entity which defines its properties and its

functions. Like Human Being, having body parts, and performing various actions.

The variables inside class definition are called as data members and the functions are called

member functions.

Lecture -3

Page 8: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Object

• An object is an abstraction of real world entity.

• It may represent a person, a place, a number, an icon a window, a browser, a list, a vector or something elsethat can be modelled.

• Ex: object : EMPLOYEE

• Data : Name

Designation

Age

Functions:

Gross_salary

Total_Deduction

Print_salary

Lecture -3

Page 9: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Accessing data members

• Syntax of input/output

• cin and cout

• Example Programs

Lecture -3

Page 10: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Variables

Variables in C++ can be declared anywhere inside a function and not necessarily at its

very beginning.

Reference variable syntax

• When a variable is declared as reference, it becomes an alternative name for an

existing variable.

• A variable can be declared as reference by putting ‘&’ in the declaration.

Lecture-4

Page 11: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

#include <iostream.h>

void main(){

int x=3;int &y=x;cout <<“x=“<<x<<endl<<“y=“<<y<<endl;y=7;cout <<“x=“<<x <<endl<<“y=“<<y<<endl;

}

O/Px=3y=3x=7Y=7

Page 12: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Data members

• Members Functions

• Function overloading

Lecture -5

Page 13: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Array of objects

• Syntax

• Example Programs

• Namespaces

Lecture -6

Page 14: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Namespace

Namespace is a container for identifiers.

It puts the names of its members in a distinct space so that they don't conflict with the names in other

namespaces or global namespace.

Syntax:

using namespace std;

In the above syntax "std" is the namespace where ANSI C++ standard class libraries are defined.

Even own namespaces can be defined.

Syntax:

namespace namespace_name

{

//Declaration of variables, functions, classes, etc.

• }

Lecture -6

Page 15: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Nested classes

Lecture -7

Page 16: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Constructors

• Constructors are of three types :

• 1. Default Constructor

• 2. Parameterized Constructor

• 3. Copy Constructor

• Default Constructor

Default constructor is the constructor which doesn't take any argument. It has noparameter.

Syntax :

class_name ()

{

Constructor Definition

}

Lecture -8

Page 17: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Parameterized Constructor

These are the constructors with parameter. Using this Constructor you can provide different

values to data members of different objects, by passing the appropr.iate values as argument.

• Example :

• class Cube

• {

• int side;

• public:

• Cube(int x) // parameterized constructor

• {

• side=x;

• }

• };

Lecture -8

Page 18: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Copy constructor

A copy constructor in C++ programming language is used to reproduce an identical copy of an original existingobject.

It is used to initialize one object from another of the same type.

• #include<iostream>

• using namespace std;

• class copycon

• {

• int copy_a,copy_b; // Variable Declaration

• public:

• copycon(int x,int y)

• {

• //Constructor with Argument

• copy_a=x;

• copy_b=y; // Assign Values In Constructor

• }

Lecture -8

Page 19: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• void Display()

• {

• cout<<"\nValues :"<< copy_a <<"\t"<< copy_b;

• } };

• int main()

• {

• copycon obj(10,20);

• copycon obj2=obj; //Copy Constructor

• cout<<"\nI am Constructor";

• obj.Display(); // Constructor invoked.

• cout<<"\nI am copy Constructor";

• obj2.Display();

• return 0;

• }

Lecture -8

Page 20: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Object Oriented Programming using Java

Module -2

Introduction to Java

Page 21: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture 9

Java’s Magic: The Byte code

Page 22: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Java’s Magic: The Bytecode

•Java to solve both the security and the portability problems

using bytecode

• Bytecode isa highly optimized set of instructions designed to

be executed by the Java run-time system, which is called the

Java Virtual Machine (JVM).

• In essence, the original JVM was designed as an interpreter

for bytecode.

• SUN supplies Hotspot which provides a Just-In-Time (JIT)

compiler for bytecode

Page 23: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture 10

Java Buzz words

Page 24: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

The Java Buzzwords

• Simple• Secure• Portable• Object-oriented• Robust• Multithreaded• Architecture-neutral• Interpreted• High performance• Distributed• Dynamic

Page 25: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Object-oriented programming

• Object-oriented programming (OOP) is at thecore of Java.

• Two Paradigmsprogram can be conceptually organized around its code oraround its data

• some programs are written around “what is happening” andothers are written around “who is being affected.”

• These are the two paradigms that govern how a program isconstructed

• The first way is called the process-oriented model.

Page 26: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Continued……………• The process-oriented model can be thought of as

code acting on data.

• Procedural languages such as C employ this model

• problems with this approach appear as programsgrow larger and more complex.

• Object-oriented programming organizes a programaround its data (that is objects)

• An object-oriented program can be characterized asdata controlling access to code

Page 27: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

The Three OOP Principles• Encapsulation

Encapsulation is the mechanism that bindstogether code and the data it manipulates.

• InheritanceInheritance is the process by which one objectacquires the properties of another object

• PolymorphismPolymorphism (from Greek, meaning “manyforms”) is a feature that allows one interface tobe used for a general class of actions.

Page 28: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture 11

Sample JAVA Program

Page 29: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Simple Program

/*This is a simple Java program.Call this file "Example.java".*/class Example {// Your program begins with a call to main().public static void main(String args[]) {System.out.println("This is a simple Java program.");}}

Page 30: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Compiling running the Program

C:\>javac Example.java

C:\>java Example

When the program is run, the following output is displayed:

This is a simple Java program.

• When Java source code is compiled, each individual class isput into its own output file named after the class and using the.class extension.

• class Example {

This line uses the keyword class to declare that a new classis being defined. Example is an identifier that is the name ofthe class.

The entire class definition, including all of its members, willbe between the opening curly brace ({) and the closing curlybrace (})

Page 31: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Continued• public static void main(String args[]) {

This line begins the main( ) method. As the commentpreceding it suggests, this is the line at which the programwill begin executing.

• The public keyword is an access specifier, which allows theprogrammer to control the visibility of class members.

• The keyword static allows main( ) to be called without havingto instantiate a particular instance of the class

• main( ) is called by the Java Virtual Machine before anyobjects are made

• The keyword void simply tells the compiler that main( ) doesnot return a value.

Page 32: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture 12

Data types

Page 33: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Data TypesThe Primitive Types• Java defines eight primitive types of data: byte, short, int, long,

char, float, double, and boolean.

These can be put in four groups:

• Integers This group includes byte, short, int, and long, which

are for whole-valued signed numbers.

Java does not support unsigned, positive-only integers

• Floating-point numbers This group includes float and double,

which represent numbers with fractional precision.

Page 34: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Floating-point numbers, also known as real numbers, are used

when evaluating expressions that require fractional precision

• There are two kinds of floating-point types, float and double,

which represent single- and double-precision

numbers, respectively. Their width and ranges are shown here:

Page 35: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Data types Continued….Characters This group includes char, which represents symbols in a character

set, like letters and numbers.

Boolean This group includes boolean, which is a special type for representing

true/false values

Page 36: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Here is a program that demonstrates char variables:

// Demonstrate char data type.

class CharDemo {

public static void main(String args[]) {

char ch1, ch2;

ch1 = 88; // code for X

ch2 = 'Y';

System.out.print("ch1 and ch2: ");

System.out.println(ch1 + " " + ch2);

}

}

Page 37: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture 13

Variable

Page 38: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Variables• The variable is the basic unit of storage in a Java program.

• A variable is defined by the combination of an identifier, a type, andan optional initializer.

• In addition, all variables have a scope, which defines their visibility,and a lifetime.

• The basic form of a variabletype identifier [ = value][, identifier [= value] ...] ;

The type is one of Java’s atomic types, or the name of a class orinterface

The identifier is the name of the variable.

int a, b, c; // declares three ints, a, b, and c.int d = 3, e, f = 5; // declares three more ints, initializing// d and f.byte z = 22; // initializes z.double pi = 3.14159; // declares an approximation of pi.char x = 'x'; // the variable x has the value 'x'.

Page 39: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• The Scope and Lifetime of Variables

• Java allows variables to be declared within any block.• a block is begun with an opening curly brace and ended by a closing curly brace. A block

defines a scope.• A scope determines what objects are visible to other parts of your program. It also

determines the lifetime of those objects.• To understand the effect of nested scopes, consider the following program:

• // Demonstrate block scope.class Scope {public static void main(String args[]) {int x; // known to all code within mainx = 10;if(x == 10) { // start new scopeint y = 20; // known only to this block// x and y both known here.System.out.println("x and y: " + x + " " + y);x = y * 2;}// y = 100; // Error! y not known here// x is still known here.System.out.println("x is " + x);}}

Page 40: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Type Conversion and Casting• If the two types are compatible, then Java will perform the

conversion automatically.

example, it is always possible to assign an int value to a longvariable(automatic conversion )

• there is no automatic conversion defined from double to byte

• it is still possible to obtain a conversion between incompatibletypes using a cast, which performs an explicit conversion betweenincompatible types.

• Java’s Automatic Conversions

• When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:

• The two types are compatible.

• The destination type is larger than the source type.

Page 41: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• When these two conditions are met, a widening conversion

takes place. For example, the int type is always large enough

to hold all valid byte values.

• To create a conversion between two incompatible types, you

must use a cast. A cast is simply an explicit type conversion. It

has this general form:(target-type) value

• target-type specifies the desired type to convert the specifiedvalue to

int a;

byte b;

b = (byte) a;

• Java automatically promotes each byte, short, or char operand to int when evaluating an expression

Page 42: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

// Demonstrate casts.

class Conversion {

public static void main(String args[]) {

byte b;

int i = 257;

double d = 323.142;

System.out.println("\nConversion of int to byte.");

b = (byte) i;

System.out.println("i and b " + i + " " + b);

System.out.println("\nConversion of double to int.");

i = (int) d;

System.out.println("d and i " + d + " " + i);

System.out.println("\nConversion of double to byte.");

b = (byte) d;

System.out.println("d and b " + d + " " + b);}}

This program generates the following output:

Conversion of int to byte.

i and b 257 1

Conversion of double to int.

d and i 323.142 323

Conversion of double to byte.

d and b 323.142 67

Page 43: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture 14

Arrays

Page 44: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Arrays• An array is a group of like-typed variables that are referred to

by a common name.

• Arrays of any type can be created and may have one or moredimensions. A specific element in an array is accessed by itsindex.

• Arrays offer a convenient means of grouping relatedinformation.

One-Dimensional Arrays

• A one-dimensional array is, essentially, a list of like-typedvariables

• To create an array, you first must create an array variable ofthe desired type.

• general form of a one-dimensional array declaration is

type var-name[ ]; type declares the base type of the array

array-var = new type[size];

Page 45: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• type specifies the type of data being allocated, size specifies thenumber of elements in the array

• array-var is the array variable that is linked to the array

Example int month_days[]; month_days = new int[12];

After this statement executes, month_days will refer to an array of12 integers. all elements in the array will be initialized to zero.

• // An improved version of the previous program.

class AutoArray {

public static void main(String args[]) {

int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,

30, 31 };

System.out.println("April has " + month_days[3] + " days.");

}

}

Multidimensional Arrays

• In Java, multidimensional arrays are actually arrays of arrays

Page 46: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• To declare a multidimensional array variable, specify each additional index using another set of square brackets.

• For example, the following declares a twodimensional array variable called twoD.

int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD

// Demonstrate a two-dimensional array.

class TwoDArray {

public static void main(String args[]) {

int twoD[][]= new int[4][5];

int i, j, k = 0;

for(i=0; i<4; i++)

for(j=0; j<5; j++) {

twoD[i][j] = k;

k++;

}

for(i=0; i<4; i++) {

for(j=0; j<5; j++)

System.out.print(twoD[i][j] + " ");

System.out.println();

}

}

}

This program generates the following output:

0 1 2 3 4

5 6 7 8 9

10 11 12 13 14

15 16 17 18 19

Page 47: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture 15

Operator

Page 48: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• Java provides a rich operator environment.

Most of its operators can be divided into the

four groups: arithmetic, bitwise, relational,

and logical.

• Java also defines some additional operators

that handle certain special situations.

• Relational opearators

Page 49: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,
Page 50: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

The Bitwise Operators

Page 51: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture 16

Selection Statement

Page 52: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Java’s Selection Statements

if (condition) statement1;

else statement2;Nested ifs

Anested if is an if statement that is the target of another if or else.

if(i == 10) {

if(j < 20) a = b;

if(k > 100) c = d; // this if is

else a = c; // associated with this else

}

else a = d;

Page 53: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

The if-else-if Ladder

A common programming construct that is based upon a sequence of nested ifs is the

if-else-if ladder. It looks like this:if(condition)statement;else if(condition)statement;else if(condition)statement;...elsestatement;

Page 54: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

switch

• The switch statement is Java’s multiway branch statement.

• It provides an easy way to dispatch execution to different parts of your code based on the value of an expression

switch (expression) {

case value1:

// statement sequence

break;

case value2:

// statement sequence

break;

...

case valueN:

Page 55: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

• The general form of the for-each version of the for is shown here: for(type itr-var : collection) statement-block

• Jump StatementsJava supports three jump statements: break, continue, and return. These statements transfer control to another part of your program

class BreakLoop3 {public static void main(String args[]) {for(int i=0; i<3; i++) {System.out.print("Pass " + i + ": ");for(int j=0; j<100; j++) {if(j == 10) break; // terminate loop if j is 10System.out.print(j + " ");}System.out.println();}System.out.println("Loops complete.");}}

Page 56: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Using break as a Form of GotoIn addition to its uses with the switch statement and loops, the break statement

can also be employed by itself to provide a “civilized” form of the gotostatement

The general form of the labeled break statement is shown here: break label

// Using break to exit from nested loops

class BreakLoop4 {

public static void main(String args[]) {

outer: for(int i=0; i<3; i++) {

System.out.print("Pass " + i + ": ");

for(int j=0; j<100; j++) {

if(j == 10) break outer; // exit both loops

System.out.print(j + " ");

}

System.out.println("This will not print");

}

System.out.println("Loops complete.");

}

}

Page 57: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Using continue• Sometimes it is useful to force an early iteration of a loop

• you might want to continue running the loop but stopprocessing the remainder of the code in its body for thisparticular iteration

// Demonstrate continue.

class Continue {

public static void main(String args[]) {

for(int i=0; i<10; i++) {

System.out.print(i + " ");

if (i%2 == 0) continue;

System.out.println("");

}

}

}

Page 58: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Object Oriented Programming using Java

Module-3

Classes, Inheritance, Exceptions, Packages and Interfaces

Page 59: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-17

Classes

• Definition

• Declaration of class and objects with syntax

• Types of classes

• Example program

Page 60: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-17 Class Fundamentals• class is a template for an object, and an object is an instance of a class. Because an

object is an instance of a class, you will often see the two words object and instanceused interchangeably.

• A class is declared by use of the class keywordclass classname {type instance-variable1;type instance-variable2;// ...type instance-variableN;type methodname1(parameter-list) {// body of method}type methodname2(parameter-list) {// body of method}// ...type methodnameN(parameter-list) {// body of method}}

Page 61: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

class Box {

double width;

double height;

double depth;

}

// This class declares an object of type Box.

class BoxDemo {

public static void main(String args[]) {

Box mybox = new Box();

double vol;

// assign values to mybox's instance variables

mybox.width = 10;

mybox.height = 20;

mybox.depth = 15;

// compute volume of box

vol = mybox.width * mybox.height * mybox.depth;

System.out.println("Volume is " + vol);

}}

Page 62: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-17 Declaring Objects• when you create a class, you are creating a new data type. You can use this type to

declare objects of that type. However, obtaining objects of a class is a two-step

process.

• First, you must declare a variable of the class type. This variable does not define an

object. Instead, it is simply a variable that can refer to an object.

• Second, you must acquire an actual, physical copy of the object and assign it to

that variable. You can do this using the new operator.

• The new operator dynamically allocates (that is, allocates at run time) memory for

an object and returns a reference to it.

Box mybox; // declare reference to object

mybox = new Box(); // allocate a Box object

• The first line declares mybox as a reference to an object of type Box.

• After the second line executes, you can use mybox as if it were a Box object. But inreality, mybox simply holds the memory address of the actual Box object

Page 63: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

•Here, class-var is a variable of the class type being created. The classname is the nameof the class that is being instantiated.• The class name followed by parentheses specifies the constructor for the class.• A constructor defines what occurs when an object of a class is created. Constructorsare an important part of all classes and have many significant attributes.

•Introducing MethodsThis is the general form of a method:type name(parameter-list) {// body of method}Methods that have a return type other than void return a value to the calling routine using the following form of the return statement:return value;

Box b1 = new Box();Box b2 = b1;

Page 64: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-18

Inheritance

• The derivation of one class from another class called inheritance.

• Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

• Super class

• Sub class

Page 65: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-18

Types of inheritance

Page 66: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-18

Page 67: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-18

Page 68: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-19

• Why java does not support multiple inheritance.

• Example program for multiple inheritance.

Page 69: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-19

Interface

• Definition and Declaration of interface.

• Example program for interface.

• Using interface, multiple inheritance can be implemented in java.

• Example program for multiple inheritance.

Page 70: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-20

Usage of java super Keyword

• super can be used to refer immediate parent class instance variable.

• super can be used to invoke immediate parent class method.

• super() can be used to invoke immediate parent class constructor.

• Example program.

Page 71: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Contd…..The this Keyword• Sometimes a method will need to refer to the object that invoked it.

• To allow this, Java defines the this keyword. this can be used inside any methodto refer to the current object. That is, this is always a reference to the object onwhich the method was invoked

• To better understand what this refers to, consider the following version of Box( ):

// A redundant use of this.

Box(double w, double h, double d) {

this. width = w; this. height = h; this. depth = d; }

Instance Variable Hiding• it is illegal in Java to declare two local variables with the same name inside

the same or enclosing scopes

• // Use this to resolve name-space collisions.• Box(double width, double height, double depth) {• this.width = width;• this.height = height;• this.depth = depth;• }

Page 72: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Contd….. Garbage Collection• Since objects are dynamically allocated by using the new operator,

objects are destroyed and their memory released for laterreallocation

• It works like this: when no references to an object exist, that objectis assumed to be no longer needed, and the memory occupiedby the object can be reclaimed.

• The finalize( ) Method

Sometimes an object will need to perform some action when it isdestroyed

• To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class.

• Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.

Page 73: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-21

Method Overriding in Java• If subclass (child class) has the same method as declared in

the parent class, it is known as method overriding in java.

Rules for Java Method Overriding• method must have same name as in the parent class• method must have same parameter as in the parent class.• must be IS-A relationship (inheritance). Example program.

Page 74: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-22

Exception Handling

• The exception handling in java is one of thepowerful mechanism to handle the runtimeerrors so that normal flow of the applicationcan be maintained.

• What is exception

• In java, exception is an event that disrupts thenormal flow of the program. It is an objectwhich is thrown at runtime.

Page 75: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-22

What is exception handling

• Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL.

• Running out of memory

• Resource allocation errors

• Inability to find files

• Problems in network connectivity

Page 76: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-22

Page 77: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-23

Types of Exception• There are mainly two types of exceptions:

checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception2. Unchecked Exception3. Error

Page 78: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-23

There are 5 keywords used in java exception handling.

1. try

2. catch

3. finally

4. throw

5. throws

Page 79: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-24

Packages in JAVA A java package is a group of similar types of classes, interfaces and

sub-packages. Package in java can be categorized in two form, • built-in package.• user-defined package. • There are many built-in packages such as java, lang, awt, javax,

swing, net, io, util, sql etc.

Advantage of Java Package • Java package is used to categorize the classes and interfaces so that

they can be easily maintained. • Java package provides access protection. • Java package removes naming collision.

Page 80: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-24

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

Page 81: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Object Oriented Programming using Java

Module-4

The Applet and Multi-Threaded Programming

Page 82: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-25

Introduction• Applet

– Program that runs in • appletviewer (test utility for applets)• Web browser (IE, Communicator)

– Executes when HTML document containing applet is opened

• Sample Applets– Provided in Java 2 Software Development Kit (J2SDK)– Source code included (.java files)– Located in demo directory of J2SDK install

Page 83: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-25

• Running applets– In command prompt, change to subdirectory of appletcd directoryName

– There will be an HTML file used to execute applet– type appletviewer example1.html

– Applet will run, Reload and Quit commands under Applet menu

• Example applets– Tic-Tac-Toe– Drawing programs– Animations– See Fig. 24.8

Page 84: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-25

• Create our own applet– Print "Welcome to Java Programming!"

– import javax.swing.JApplet

• Needed for all applets

– import java.awt.Graphics

• Allows program to draw graphics (lines, ovals, text) on an applet

– Like applications, applets have at least one class definition

• Rarely create applets from scratch– Use pieces of class existing definitionspublic class WelcomeApplet extends JApplet {

– extends ClassName - class to inherit from• In this case, inherit from class JApplet

Page 85: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-26

• Types of Applets

• Applet basics

• Applet Architecture.

Page 86: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-26

• An Applet skeleton

• Simple Applet display methods

Page 87: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-27

• Classes– Templates/blueprints create or instantiate objects

• Objects - locations in memory to store data

• Implies that data and methods associated with object

• Methods– paint, init, and start called automatically

for all applets• Get "free" version when you inherit from JApplet

• By default, have empty bodies

• Must override them and define yourself

Page 88: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-27

• Requesting repainting

• Using the Status Window

• The HTML APPLET tag

• Passing parameters to Applets,

Page 89: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-28

• getDocumentbase()

• getCodebase()

Page 90: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-29

• Introduction to Multi-Threaded Programming

• What are threads?

Page 91: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-30

• How to make the classes threadable

• Extending threads

• Implementing runnable

Page 92: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-31

• Synchronization

• Changing state of the thread

Page 93: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-32

• Bounded buffer problems

• read-write problem.

Page 94: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Object Oriented Programming using Java

Module-5

Event Handling and Swings

Page 95: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-33

Event Handling

• Change in the state of an object is known as event.

• event describes the change in state of source.

• Events are generated as result of user interaction with

the graphical user interface components.

• For example, clicking on a button, moving the mouse,

entering a character through keyboard, selecting an

item from list, scrolling the page are the activities that

causes an event to happen.

Page 96: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-33

delegation event model has the following key participants namely:

• Event: Event is an object that describes the state change.

• Event Source: An Event Source is an object which originates or "fires" events.

• Event Listener: A listener is an object which will be notified when an event occurs.

Page 97: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-33

Java Event classes and Listener interfaces

Event Classes Listener Interfaces• ActionEvent ActionListener• MouseEvent MouseListener and

MouseMotionListener• MouseWheelEvent MouseWheelListener• KeyEvent KeyListener• ItemEvent ItemListener• TextEvent TextListener• AdjustmentEvent AdjustmentListener• WindowEvent WindowListener

Page 98: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-34

Source of Events

KeyEvent

• A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants:

• KEY_PRESSED

• KEY_RELEASED, and

• KEY_TYPED.

Page 99: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-34

MouseEvent

There are eight types of mouse events.

The MouseEvent class defines the following that can be used to identifythem:• MOUSE_CLICKED The user clicked the mouse.• MOUSE_DRAGGED The user dragged the mouse.• MOUSE_ENTERED The mouse entered a component.• MOUSE_EXITED The mouse exited from a component.• MOUSE_MOVED The mouse moved.• MOUSE_PRESSED The mouse was pressed.• MOUSE_RELEASED The mouse was released.• MOUSE_WHEEL The mouse wheel was moved.

Page 100: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-35

KeyListener interface

This interface defines following methods

void keyPressed(KeyEvent ke)

void keyReleased(KeyEvent ke)

void keyTyped(KeyEvent ke)

Page 101: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-35

MouseListener interfaceThis interface defines following methodsvoid mouseClicked(MouseEvent me)void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me)

MouseMotionListener interfaceThis interface defines following methodsvoid mouseDragged(MouseEvent me)void mouseMoved(MouseEvent me)

Page 102: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-36

Adaptor Classes

• An adapter class provides the default implementation of all methods in an event listener interface.

• Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface.

Page 103: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-36

Adaptor class Listener Interface

• ComponentAdapter ComponentListener

• ContainerAdapter ContainerListener

• FocusAdapter FocusListener

• MouseAdapter KeyListener

• MouseMotionAdapter MouseListener

• WindowAdapterMouseMotionListener

Page 104: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-37

The origins of Swing

• Developed in 1997.

• Included as a part java Foundation Classes(JFC).

• Swing was initially available for use with Java 1.1.

• Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Page 105: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-37

Two key Features of Swing

• Light weight Components.

• Pluggable Look and Feel.

Page 106: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-37

Lightweight• Swing is considered lightweight because it is fully

implemented in Java, without calling the nativeoperating system for drawing the graphical userinterface components.

Heavyweight• On the other hand, AWT (Abstract Window Toolkit) is

heavyweight toolkit, as it merely makes calls to theoperating system in order to produce its GUIcomponents.

Page 107: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-38

Components and ContainersA Swing GUI consists of two key items: Components and

Containers.

Components

• Independent visual control.• Derived from JComponent class.• JComponent provides the functionality that is common to

all components.• All swing components are represented by the classes

defined in javax.swing.

Page 108: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-38

Container• Container holds group of components.• All Swing GUIs will have at least one container.• A Container can hold another container.Two types of Container• Top level Container

e.g. JFrame,JApplet,JWindow,JDialog.• Light weight Container

e.g. JPanel,JLabel etc

Page 109: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-39

Swing Packages

Page 110: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-39

Simple Swing application• There are two types of Java programs in which Swing is typically

used.

Desktop application.

The applet.

Page 111: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-40

Page 112: OBJECT ORINTED PROGRAMMING WITH JAVA · 2020. 11. 25. · •Inheritance Inheritance is the process by which one object ... • Java defines eight primitive types of data: byte, short,

Lecture-40

• JTextField is the simplest Swing text component.

• It is also probably its most widely used text component. JTextField allows you to edit one line of text.

• Three of JTextField’s constructors are shown here:

JTextField(int cols)

JTextField(String str, int cols)

JTextField(String str)

– JPasswordField is a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters.