Você está na página 1de 141

INTRODUCTION TO BASIC

JAVA
What Is Java?
Java:
Is a platform and an object-oriented
language
Was originally designed by Sun
Microsystems for consumer electronics
Contains a class library
Uses a virtual machine for program
execution
JAVA BUZZWORDS
SIMPLE
OBJECT-ORIENTED
ROBUST
MULTITHREADED
ARCHITECTURE-NEUTRAL
INTERPERTED AND HIGH PERFORMANCE
DISTRIBUTED
DYNAMIC
SIMPLE
Java was designed to be easy for
professional programmer to lean and
use effectively.
Java inherits the c/c ++ syntax and many
of object-oriented features.
OBJECT-ORIENTED
Java was not designed to be source-code
compatible with any other language.
Everything is an object
ROBUST
Multiplatform environment of the web
pages extraordinary demands on a
program, because the program must
execute reliably in a variety of systems.
Failure: Memory management
Mishandled exceptional conditions (run
time error).
ARCHITECTURE-NEUTRAL
A central issue for the java designers was
the code longevity and portability.
Goal was write once;
Run any where, any time ,forever.
DISTIBUTED AND DYNAMIC
Java is designed for the distributed
environment of the internet because it
handles TCP/IP. Protocols.
Java also supports Remote Method
Invocation (RMI)
This features enables a program to invoke
methods across a network.
JAVA
JAVA CHANGED THE INTERNET
JAVA APPLETS
SECUTRITY
PORTABILITY
APPLETS

Java applets:
An applet is special kind of java program
that is designed to be transmitted over
the internet and automatically executed
by a java-compatible web browser.
SECUTRITY

Security
Java achieved this protection by confining
an applet to java execution environment
and not allowing it access to other parts
of the computer.
PORTABILITY
Portability
Portability is a major aspect of internet
because there are many different types
of computers and operating systems
connected to it.
An Object-Oriented Approach
Objects and classes
An object is a run-time representation of a thing.
A class is a static definition of things.
Class models elaborate:
Existing classes and objects
Behaviour, purpose, and structure
Relationships between classes
Relationships between run-time objects
Same models exist throughout the project.
Integration
Analysis Design Implementation
and testing

CLASS MODELS
Platform Independence
Java source code is stored as text in a .java file.
The .java file is compiled into .class files.
A .class file contains Java bytecodes (instructions).
The bytecodes are interpreted at run time.
The Java .class file is the executable code.

Compile JVM
(javac) (java)

Movie.java Movie.class Running program


Java Virtual Machine (JVM)

JVM provides the environment for running


Java programs. The JVM interprets Java
bytecodes into the native instruction set for the
machine on which the program is currently
running.
The same .class files can be executed
unaltered on any platform for which a JVM is
provided. For this reason, JVM is sometimes
referred to as a virtual processor.
Using the Java Virtual
Machine
Operating system

JVM

Application
How Does JVM Work?
The class loader loads all required classes.
JVM uses a CLASSPATH setting to locate class
files.
JVM Verifier checks for illegal bytecodes.
JVM Verifier executes bytecodes.
JVM may invoke a Just-In-Time (JIT) compiler.
Memory Manager releases memory used by the
dereferenced object back to the OS.
JVM handles Garbage collection.
Garbage collection
Java the objects are dynamically allocated
by using the new operator.
The objects must be manually release by
use of an delete operator
But java take it deallocation of memory
automatically .This is accomplished by
garbage collections.
Reference object.
Using the Appropriate
Development Kit
Java2 comes in three sizes:
J2ME (Micro Edition): Version specifically
targeted at the consumer space
J2SE (Standard Edition): Complete
ground-up development environment for
the Internet
J2EE (Enterprise Edition): Everything in
the J2SE plus an application server and
prototyping tools
Object-Oriented Principles
Object-Oriented
programming
Object-Oriented programming(o o p)s
Oops organizes a program around its
data (that is objects) a set of well
defined interface to that data.
An object-oriented program can be
characterized as data controlling access
to the code.
oops
ABSTRACTION
ENCAPSULATION
INHERITANCE
POLYMORPHISM
ABSTRACTION

Essential element of oops programming is


abstraction.
Humans manage complexity through
abstraction.
Ex. Car
Car has thousand of part, People think of it as a well defined object
with its own unique behavior. This abstraction allows people to
use a car to drive without being of how the engine, transmission
and braking system work
ENCAPSULATION
Encapsulation is the technique of making the fields in a class private and
providing access to the fields via public methods. If a field is declared
private, it cannot be accessed by anyone outside the class, thereby
hiding the fields within the class. For this reason, encapsulation is also
referred to as data hiding.
Encapsulation can be described as a protective barrier that prevents the
code and data being randomly accessed by other code defined outside
the class. Access to the data and code is tightly controlled by an
interface.
The main benefit of encapsulation is the ability to modify our
implemented code without breaking the code of others who use our
code. With this feature Encapsulation gives maintainability, flexibility and
extensibility to our code .
INHERITANCE

Inheritance can be defined as the process where one


object acquires the properties of another. With the use
of inheritance the information is made manageable in
a hierarchical order.
When we talk about inheritance, the most commonly
used keyword would be extends and implements.
These words would determine whether one object IS-
A type of another. By using these keywords we can
make one object acquire the properties of another
object.
POLYMORPHISM

Polymorphism is the ability of an object


to take on many forms. The most
common use of polymorphism in OOP
occurs when a parent class reference is
used to refer to a child class object.
Example polymorphism
The method with a java program applies
to the general concept
Classes and Objects
What Are Classes and
Objects?
A class:
Models an abstraction of objects
Defines the attributes and behaviors of
objects
Is the blueprint that defines an object
An object:
Is stamped out of the class mold
Is a single instance of a class
Retains the structure and behavior
of a class
What Is an Object?
An object is something tangible, something
that can be seen or touched, or something
that can be alluded to and thought about.
Object-oriented programs consist of several
objects. These objects communicate with each
other by sending messages from one object to
another.
In a true object-oriented program, that is all
you have: a coherent group of communicating
objects. New objects are created when
needed, old ones are deleted, and existing
objects carry out operations by sending
messages.
An Objects Attributes
Maintain Its State
Objects have knowledge about their current state.
Each piece of knowledge is called an attribute.
The values of attributes dictate the objects state.

Object: My blue pen Attribute: Ink amount

Object: Acme Bank ATM Attribute: Cash available


Objects Have Behavior
An object exists to provide behavior
(functionality) to the system.
Each distinct behavior is called an operation.

Object: My blue pen Operation: Write

Object: Acme Bank ATM Operation: Withdraw


What Are Classes?
A class is a model of abstraction from real-
world objects. A class defines the properties
and behavior of a set of objects. A class
denotes a category of objects and acts as a
blueprint for creating that type of object.
Defining a Class
Class definitions typically include:
Access modifier
Class keyword
Instance fields
Constructors
Instance methods
Class fields
Class methods
Access modifier: Specifies the availability of the class
from other classes
Class keyword: Indicates to Java that the following code
block defines a class
Instance fields: Contain variables and constants that are
used by objects of the class
Constructors: Are methods having the same name as
the class, which are used to control the initial state of any
class object that is created
Instance methods: Define the functions that can act
upon data in this class
Class fields: Contain variables and constants that
belong to the class and are shared by all objects of that
class
Class methods: Are methods that are used to control the
values of class fields
Rental Class: Example
Access modifier

public class Rental { Declaration


//Class variable
static int lateFee;
// Instance variables Instance
int rentalId; variable
String rentalDate;
float rentalAmountDue;

// Instance methods Instance
float getAmountDue (int rentId) { method

}

}
THE BASIC FORM OF CLASS
DEFINITION
CLASS NAME
{
//
}
A java source file should contain at least one class definition.
Defining class:
A class is the fundamental building block of an object oriented
language such as java.
When you instantiate a class, you create an object .
The data associated with the class is stored in variables.
The behavior associated with class or object is implemented with
methods.
Public class Example {
public static void main (String args []) {
System.out.println(This is a simple
java program");
}
}
Describing the main method
Every java application must contain a main method like
Public static void main(String args[ ])
It contains 3 modifiers
Public indicates that the main method can be called by
any code outside the program.
Static indicates that the main method is a class method.
The method can be called directly from the other
classes without first creating the object.
Void indicates that the main method doesnt return any
value.
About System.out.println
Understanding System.out.println()
System is a class in the java.lang package.
out is a public final static (class) variable.
Declared as a PrintStream object reference
println() is an overloaded method of the
PrintStream class.
PrintStream is a FilterOutputStream that
subclasses OutputStream.
System.err is also provided as a PrintStream
object reference to write to standard error.
Creating Code Blocks
Enclose all class declarations.
Enclose all method declarations.
Group other related code segments.

public class SayHello {


public static void main(String[] args) {
System.out.println("Hello world");
}
}
Declaring Variables
You can declare variables anywhere in a class
block, and outside any method.
You must declare variables before they are used
inside a method.
It is typical to declare variables at the beginning of
a class block.
The scope or visibility of variables is determined in
the code block.
You must initialize method variables before using
them.
Class and instance variables are automatically
initialized.
Rules for Creating
Statements
Use a semicolon to terminate statements.
Define multiple statements within braces.
Use braces for control statements.
Compiling and Running
a Java Application
To compile a .java file:
prompt> javac SayHello.java
compiler output

To execute
prompt> a .class
java SayHello file:
Hello world
prompt>

Remember that case matters.


The CLASSPATH Variable
Is defined in the operating system
Directs the JVM and Java applications
where to find .class files
References built-in libraries or user-
defined libraries
Enables interpreter to search paths, and
loads built-in classes before user-defined
classes
Can be used with javac and java
commands
Exploring Primitive Data
Types
and Operators
Reserved Keywords
boolean abstract break class
byte final case extends
char native catch implements
double private continue interface
float protected default throws
int public do
long static else import
short synchronized finally package
void transient for
volatile if
instanceof
true strictfp return
new
false switch
super
null throw
this
try
while
What Are Variables?
A variable is a basic unit of storage.
Variables must be explicitly declared.
Each variable has a type, an identifier, and
a scope.

Title: Blue
Moon
Type
Identifier
int myAge; Initial value
boolean isAMovie;
float maxItemCost = 17.98F;
Declaring Variables
Basic form of variable declaration:
type identifier [ = value];

public static void main(String[] args) {


int itemsRented = 1;
float itemCost;
int i, j, k;
double interestRate;
}

Variables can be initialized when declared.


Local Variables
Local variables are defined only within a method
or code block.
They must be initialized before their contents are
read or referenced.
class Rental {
private int instVar; // instance variable
public void addItem() {
float itemCost = 3.50F; // local variable
int numOfDays = 3; // local variable
}
}
public class Example2variable {

public static void main(String[ ] args) {


int num; //this declares a variable called num
num = 100 ; //this assigns num the value 100
System.out.println("This is number:" + num);
num = num *2 ;
System.out.print("The value of number num *2 is :");
System.out.println(num);
}
}
Defining Variable Names
Variable names must start with a letter of
the alphabet, an underscore, or a $
symbol.
a Other characters
item_Cost may include digits.
item#Cost item-Cost
itemCost _itemCost item*Cost abstract
item$Cost itemCost2 2itemCost

Use meaningful names for variables, such as


customerFirstName and
ageNextBirthday.
import java.util.Scanner;
public class gettinginput {

public static void main(String[ ] args) {


Scanner value = new Scanner(System.in);
System.out.println(value.nextLine());
}

}
GETTING USER INPUT
import java.util.Scanner;
public class calcu {
public static void main (String args[]){
Scanner val1 = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Enter the first num:");
fnum = val1.nextDouble();
System.out.println("Enter the second num:");
snum = val1.nextDouble();
answer = fnum + snum;
System.out.println(answer);
}
}
DATA TYPE,VARIABLES AND
ARRAYS
Primitive data types
Byte
Short
Int
Long
Char
Float
Double
Boolean
INTEGERS
Long 64
Long is signed 64 bit type and is used for
where an int type is not large enough to
hold the desired value.
The range of long is quite large.
public class Light {
// compute distance light travels using long variables.
public static void main(String[] args) {
int lightspeed;
long days;
long seconds;
long distance;
//aproximate speed of the light in miles per second
lightspeed = 186000;
days = 1000;
seconds = days * 24 * 60 * 60 ;
distance = lightspeed *seconds;
System.out.print("In " +days);
System.out.print(" days light will travel about");
System.out.println(distance + " miles");
Byte
The smallest integer type is byte.
This is a singed 8-bit type has a range form
-128 to 127.
Byte variables are declared by use of the
byte keyword.
Example
Byte b,c;
Short
Short is 16-bit type it range from -32768 to
32767
Example short s;
Int
The most commonly used integer type is
int range -2147483648 to 2147483647
Float
32 bits range 1.4e-045 to 3.4e+038
Double
64 bits store range 4.9e-324 to 1.8e+308
Characters
Java char is 16-bit type The range of char
is 0 65,536
There are not negative char
Type conversion and casting
If the 2 types are compatible,java performs automatic
conversion.
For example, an int value can be assigned to a long
variable.
Int x=5;
Long y=x; //OK
However, not all types are compatible, and thus not all
type conversions are implicitly allowed.
For example, there is no conversion defined from
double to byte.
Byte z= 15.2 //ERROR!
Examining Conversions and
Casts
Java automatically converts a value of one
numeric type to a larger type.

byte
short
int
char long

Java doesshort
not automatically downcast.
byte int long
char
Using Arrays and
Collections
What Is an Array?
An array is a collection of variables of the same type.
Each element can hold a single item.
Items can be primitives or object references.
The length of the array is fixed when it is created.

[0] 1
[0] Action
[1] 2
[1] Comedy
[2] 4
[2] Drama
[3] 8
Creating an Array of
Primitives
Null
1. Declare the array: arrayName
type[] arrayName;
or
type arrayName[]; 0
arrayName
0
0
type is a primitive, such as int and so on.
2. Create the array object:
// Create array object syntax 1
arrayName
arrayName = new type[size]; 2
3. Initialize the array elements 4
(optional).
Declaring an Array of
Primitives
Create a variable to reference the array object:

int[] powers; // Example

When an array variable is declared:


Its instance variable is initialized to null until the
array object has been created

powers null

Its method variable is unknown until the object is


created
Creating an Array Object for
an Array of Primitives
Create an array of the required length and
assign it to the array variable:
int[] powers; // Declare array variable
powers = new int[4]; //Create array object

The array object is created by using the new


operator.
0
The contents of an array of primitives are 0
powers
initialized automatically. 0
0
Initializing Array Elements
Assign values to individual elements:
arrayName[index] = value; 1 [0]
powers 0 [1]
powers[0] = 1;
0 [2]
0 [3]

Create and initialize arrays at


type[] arrayName = {valueList};
the same time: 2 [0]
int[] primes = {2, 3, 5, 7}; primes 3 [1]
5 [2]
7 [3]
Creating an Array of Object
References
arrVar
1. Declare the array: null

ClassName[] arrVar;
arrVar
or null
ClassName arrVar[];
null

null
2. Create the array object:
arrVar
Action
// Create array object syntax
Comedy
arrVar = new ClassName[size];
Drama

3. Initialize the objects in the array.


Initializing the Objects in the
Array
Assign a value to each array element:
// Create an array of four empty Strings
String[] arr = new String[4];
for (int i = 0; i < arr.length; i++) {
arr[i] = new String();
}

Create and initialize the array at the same


time:
String[] categories =
{"Action", "Comedy", "Drama"};
Using an Array of Object
References
Any element can be assigned to an object of the
correct type:

String category = categories[0];

Each element can be treated as an individual


object:
System.out.println
("Length is " + categories[2].length());

An array element can be passed to any method;


array elements are passed by reference.
public class arryaexaples {
public static void main(String[ ] args) {
int i[ ]=new int[10];
i[0]=87;
i[1]=457;
i[9]=450;

System.out.println(i[1]);
}
public class arrayexamples2 {
public static void main(String[ ] args) {
int i[ ]={34,56,76,78,45,334,};
System.out.println(i[2]);
}
}
public class arraytableexample3 {
public static void main(String[] args) {
System.out.println("Index\tValue");
int i[ ]={34,56,76,78,45,334,};

for (int counter=0;counter<i.length;counter++)


{
System.out.println(counter + "\t" + i[counter]); }
}
Multidimensional Arrays
Java supports arrays of arrays:
type[][] arrayname = new type[n1][n2];

int[][] mdarr = new int[4][2]; [0][0] [0][1]


mdarr[0][0] = 1;
mdarr[0][1] = 7;
mdarr
1 7
[0]
[1] 0 0

[2] 0 0

[3] 0 0
//demonstrate a two dimensional array.
class twodarray {
public static void main(String args[]) {
int x[ ][ ]=new int[4][5];
int i,j,k=0;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
{
x[i][j]= k;
k++;
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
System.out.print(x[i][j] +" ");
System.out.println();
}
}
}
Java operators
Categorizing Operators
There are five types of operators:
unary
prefix
Postfix
Infix binary operators
Ternary operators
Categorizing Operators
The built in java operators can be
grouped into:
Assignment
Arithmetic
Integer bitwise
Relational
Boolean
Using the Assignment
Operator
The result of an assignment operation is a value and
can be used whenever an expression is permitted.
The value on the right is assigned to the identifier
on the left:
int var1 = 0, var2 = 0;
var1 = 50; // var1 now equals 50
var2 = var1 + 10; // var2 now equals 60

The expression on the right is always evaluated


before the assignment.
Assignments
var1 = var2 = can
var3be= strung
50; together:
Working with Arithmetic
Operators
Perform basic arithmetic operations.
Work on numeric variables and literals.

int a, b, c, d, e;
a = 2 + 2; // addition
b = a * 3; // multiplication
c = b - 2; // subtraction
d = b / 2; // division
e = b % 2; // returns the remainder of division
Incrementing and
Decrementing Values
The ++ and -- operators increment and
decrement by 1, respectively:
int var1 = 3;
var1++; // var1 now equals 4

The ++ and -- operators can be used in two ways:


int var1 = 3, var2 = 0;
var2 = ++var1; // Prefix: Increment var1 first,
// then assign to var2.
var2 = var1++; // Postfix: Assign to var2 first,
// then increment var1.
Relational and Equality
Operators
> greater than
>= greater than or equal to
< less than
<= less than or equal to
== equal to
!= not equal to

int var1 = 7, var2 = 13;


boolean res = true;
res = (var1 == var2); // res now equals false
res = (var2 > var1); // res now equals true
Using the Conditional
Operator (?:)
Useful alternative to ifelse:
boolean_expr ? expr1 : expr2

If boolean_expr is true, the result is


expr1; otherwise, the result is expr2:
int val1 = 120, val2 = 0;
int highest;
highest = (val1 > val2) ? val1 : val2;
System.out.println("Highest value is " + highest);
Using Logical Operators
Results of Boolean expressions can be
combined by using logical operators:
&& & and (with or without short-circuit evaluation)
|| | or (with or without short-circuit evaluation)
^ exclusive or
! not

int var0 = 0, var1 = 1, var2 = 2;


boolean res = true;
highest = (val1 > val2)? val1 : val2;
res = !res;
Compound Assignment
Operators
An assignment operator can be combined
with any conventional binary operator:
double total=0, num = 1;
double percentage = .50;

total = total + num; // total is now 1
total += num; // total is now 2
total -= num; // total is now 1
total *= percentage; // total is now .5
total /= 2; // total is now 0.25
num %= percentage; // num is now 0
Concatenating Strings
The + operator creates and concatenates
strings:
String name = "Jane ";
String lastName = "Hathaway";
String fullName;
name = name + lastName; // name is now
//"Jane Hathaway"
// OR
name += lastName ; // same result
fullName = name;
Controlling Program Flow
Categorizing Basic Flow
Control Types
Flow control can be categorized into four
types:
Sequential Iteration

Selection Transfer
Using Flow Control in Java
Each simple statement terminates with a
semicolon (;).
Group statements by using the braces { }.
Each block executes as a single statement within
the flow of control structure.
{
boolean finished = true;
System.out.println("i = " + i);
i++;
}
Using the if Statement
if ( boolean_expr )
statement1;
General:
[else
statement2];

if (i % 2 == 0)
System.out.println("Even");
Examples: else
System.out.println("Odd");
if (i % 2 == 0) {
System.out.print(i);
System.out.println(" is even");
}
Nesting if Statements
if (speed >= 25)
if (speed > 65)
System.out.println("Speed over 65");
else
System.out.println("Speed >= 25 but <= 65");
else
System.out.println("Speed under 25");

if (speed > 65)


System.out.println("Speed over 65");
else if (speed >= 25)
System.out.println("Speed greater to 65");
else
System.out.println("Speed under 25");
Defining the switch
Statement
switch ( integer_expr ) {

case constant_expr1:
statement1;
break;
The switch
case constant_expr2: statement is useful
statement2; when selecting an
break; action from several
[default: alternative integer
statement3;] values.
} Integer_expr
must be byte, int,
char, or short.
More About the switch
Statement
switch (choice) {
case labels
case 37:
must be
System.out.println("Coffee?");
constants.
Use break break;
to jump out
of a switch. case 45:
It is System.out.println("Tea?");
recommend break;
ed to always
provide a default:
default. System.out.println("???");
break;
}
Looping in Java
There are three types of loops in Java:
while
dowhile
for
All loops have four parts:
Initialization
Iteration condition
Body
Termination
Using the while Loop
while is the simplest loop statement and
contains the following general form:
while ( boolean_expr )
statement;

Example: int i = 0;
while (i < 10) {
System.out.println("i = " + i);
i++;
}
Using the dowhile Loop
dowhile loops place the test at the
end: do
statement;
while ( termination );

int i = 0;
Example:
do {
System.out.println("i = " + i);
i++;
} while (i < 10);
Using the for Loop
for loops are the most common loops:
for ( initialization; termination; iteration )
statement;

Example:

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


System.out.println(i);

How would this for loop look using a while


loop?
More About the for Loop
Variables can be declared in the initialization
part of a for loop:
for (int i = 0; i < 10; i++)
System.out.println("i = " + i);

Initialization and iteration can consist of a list


of comma-separated
for (int i = 0, j = 10; i <expressions:
j; i++, j--) {
System.out.println("i = " + i);
System.out.println("j = " + j);
}
The break Statement
Breaks out of a loop or switch statement
Transfers control to the first statement after the
loop body or switch statement
Can simplify code but must be used sparingly

while (age <= 65) {
balance = (balance+payment) * (1 + interest);
if (balance >= 250000)
break;
age++;
}

Throwing and Catching
Exceptions
Objectives
After completing this lesson, you should
be able to do the following:
Explain the basic concepts of exception
handling
Write code to catch and handle exceptions
Write code to throw exceptions
Create your own exceptions
What Is an Exception?
An exception is an unexpected event.
How Does Java Handle
Exceptions?
A method throws an exception.
A handler catches the exception.

Exception object

Handler
for this
Yes exception? No
Advantages of Java Exceptions: Separating
Error Handling Code
In traditional programming, error handling often
makes code more confusing to read.
Java separates the details of handling
unexpected errors from the main work of the
program.
The resulting code is clearer to read and,
therefore, less prone to bugs.
Advantages of Java Exceptions:
Passing Errors Up the Call Stack

Traditional error Java exceptions


handling
method1 Method1
//handle error Error //handle ex
code
method2 method2
Error Exception
code ex
method3 method3
Error
code
method4 method4
Each method checks for errors method4 throws an exception;
and returns an error code to its eventually method1 catches it.
calling method.
What to Do with an
Exception
Catch the exception and handle it.
Allow the exception to pass to the calling
method.
Catch the exception and throw a different
exception.
Catching and Handling
Exceptions
Enclose the try {
// call the method
method call in
}
a try block. catch (exception1) {
Handle each // handle exception1
exception in a }
catch block. catch (exception2) {
// handle exception2
Perform any
}
final processing finally {
in a finally // any final processing
block. }
Catching a Single Exception
int qty;
String s = getQtyFromForm();
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here
Catching Multiple Exceptions
try {
// Might throw MalformedURLException
URL u = new URL(str);
// Might throw IOException
URLConnection c = u.openConnection();
}
catch (MalformedURLException e) {
System.err.println("Could not open URL: " + e);
}
catch (IOException e) {
System.err.println("Could not connect: " + e);
}
Cleaning Up with a finally
Block
FileInputStream f = null;
try {
f = new FileInputStream(filePath);
while (f.read() != -1)
charcount++;
}
catch(IOException e) {
System.out.println("Error accessing file " + e);
}
finally {
// This block is always executed
f.close();
}
Catching and Handling Exceptions:
Guided Practice
void makeConnection(String url) {
try {
URL u = new URL(url);
}
catch (MalformedURLException e) {
System.out.println("Invalid URL: " + url);
return;
}
finally {
System.out.println("Finally block");
}
System.out.println("Exiting makeConnection");
}
Creating Exceptions
Extend the Exception class.
public class MyException extends Exception { }

public class UserFileException extends Exception {


public UserFileException (String message) {
super(message);
}
}
Example for exceptions
package expections;
import java.util.*;
public class sample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter first num");
int n1 = input.nextInt();
System.out.println("Enter Second num");
int n2 = input.nextInt();
int sum = n1/n2;
System.out.println(sum);
} catch (Exception e) {
System.out.println("Your cant do that");
} } }
Summary
In this lesson, you should have
learned how to do the following:
Use Java exceptions for robust error
handling
Handle exceptions by using try, catch,
and finally
Use the throw keyword to throw an
exception
Use a method to declare an exception in
its signature to pass it up the call stack
Inheritance
Inheritance is one of the fundamental
mechanisms of object oriented
programming.
The terms used in inheritance are
Base class
Derived class
Super keyword
A subclass can call a construct method
defined by its superclass by using the
syntax of super:

Super (parameter-list)
1.Super keyword is used to call immediate
parent.
2.Super keyword can be used with instance
members i.e., instance variables and instance
methods.
3.Super keyword can be used within
constructor to call the constructor of parent
class.
OK now lets practically implement this points
of super keyword.
class base
{
int a = 100;
}

class sup1 extends base


{
int a = 200;
void show()
{
System.out.println(a);
System.out.println(a);
}
public static void main(String[] args)
{
new sup1().show();
}
}
Output : -
200
200
class base
{
int a = 100;
}

class sup2 extends base


{
int a = 200;
void show()
{
System.out.println(super.a);
System.out.println(a);
}
public static void main(String[] args)
{
new sup2().show();
}
}
100
200
Reusing Code with
Inheritance
Objectives
After completing this lesson, you
should be able to do the following:
Define inheritance
Use inheritance to define new classes
Provide suitable constructors
Override methods in the superclass
Describe polymorphism
Use polymorphism effectively
Key Object-Oriented
Components
Inheritance
Constructors referenced by subclass
Polymorphism
Inheritance as an OO fundamental

Superclass

InventoryItem

Subclasses
Movie Game Vcr
Example of Inheritance
The InventoryItem class defines
methods and variables.
InventoryItem

Movie

Movie extends InventoryItem and can:


Add new variables
Add new methods
Override methods in InventoryItem class
Specifying Inheritance in
Java
Inheritance is achieved by specifying
which superclass the subclass extends.
public class InventoryItem {

}
public class Movie extends InventoryItem {

}

Movie inherits all the variables and


methods of InventoryItem.
If the extends keyword is missing, then
the java.lang.Object is the implicit
superclass.
What Does a Subclass Object
Look Like?
A subclass inherits all the instance
variables of its
public class InventoryItem {
superclass.
private float price; Movie
private String condition;
}
price
condition
public class
Movie extends InventoryItem { title
private String title; length
private int length;
}
Default Initialization
What happens when a
subclass object is
created?
Movie
Movie movie1 = new Movie();

If no constructors are price


condition
defined:
First, the default no-arg
constructor is called in the title
length
superclass.
Then, the default no-arg
constructor is called in the
subclass.
Method overloaded
A method name in the two classes are
same but these type signatures and
argumnets are different then we say
method is overloaded
class overload {
void sum1(int a, int b)
{
int res1=a+b;
System.out.println("The sum of two integers is "+res1);
}
void sum1(double a, double b)
{
double res2=a+b;
System.out.println("The sum of two double nos is "+res2);
}

public static void main(String args[])


{

overload o=new overload();


o.sum1(10,20);
o.sum1(10.3,20.4);
}

Specifying Additional
Methods
The superclass defines methods for all
types of InventoryItem.
The subclass can specify additional
methods that are specific to Movie.
public class InventoryItem {
public float calcDeposit()
public String calcDateDue()

public class Movie extends InventoryItem {
public void getTitle()
public String getLength()
Overriding Superclass
Methods
A subclass inherits all the methods of its
superclass.
The subclass can override a method with
its own specialized version.
The subclass method must have the same
signature and semantics as the superclass
method.
class trainer
{

void communicationskill()
{
System.out.println("Trainer 's communication should be remarkable");
}
}
class javatrainer extends trainer
{
void communicationskill()
{
System.out.println("Trainer 's communication is good");
}
}
class skills
{
public static void main(String a[])

{
javatrainer jt=new javatrainer();
jt.communicationskill();
}
}
Invoking Superclass
Methods
If a subclass overrides a method, then it
can still call the original superclass
method.
Use super.method() to call a
superclass method from the subclass.
Treating a Subclass as Its
Superclass
A Java object instance of a subclass is assignable to its
superclass definition.
You can assign a subclass object to a reference that is
declared with the superclass.

The compiler treats the object via its reference (that is, in
terms of its superclass definition).
The JVM run-time environment creates a subclass
object, executing subclass methods, if overridden.
public static void main(String[] args) {
InventoryItem item = new Vcr();
double deposit = item.calcDeposit();
}
Using the instanceof
Operator
You can determine the true type of an
object by using an instanceof operator.
An object reference can be downcast to
the correct type, if necessary.
public void aMethod(InventoryItem i) {

if (i instanceof Vcr)
((Vcr)i).playTestTape();
}
Limiting Methods and
Classes with final
You can mark a method as final to
prevent it from being overridden.
public final boolean checkPassword(String p) {

}

Youclass
public final can mark
Color { a whole class as final to
prevent it from being extended.
}
Summary
In this lesson, you should have
learned the following:
A subclass inherits all the variables and
methods of its superclass.
You can specify additional variables and
methods and override methods.
A subclass can call an overridden
superclass method by using super.
Polymorphism ensures that the correct
version of a method is called at run time.

Você também pode gostar