Anda di halaman 1dari 48

Session 1

Objectives: Object & Class. Abstract Class & Interface. Package. String. Exception Handling. Wrapper Class. Collection Frame work.
IETE

Object
Shapes

Mammals

IETE

A Dog has name, It has some color, It belongs to a breed, It may be hungry. name , color, breed, hungry are the attributes of Dog object. Dog can bark, search, eat .. Bark, search, eat define some behaviour of Dog object. Behavior (Doing Responsibility) is how an object reacts, in terms of its state changes, in response to operations performed upon it.
IETE

Class
Class Defines the attributes and behaviour of the objects. Class is the blueprint of the objects. Objects are physical entity and class is the logical construct of the objects. An object has some states. State(Knowing Responsibility) is a set of properties which can take different values at different times in the objects life. Every object has an unique identity number.
IETE

Object has following characteristics State

Behavior
Attributes

Identity

IETE

Java Objects & Class Contd.


Example: Mr. White is married. He teaches OO Software Engineering classes on Fridays. He is a part-time member of the faculty at the CS Department of the All-Smart Institute. John is enrolled in the OOSE class that Mr. White teaches. Mrs. White uses a Nano for transportation to and from the campus (she teaches Philosophy at the same institute). Class size is limited at the institute to 14 students. Janet, the sister of John is enrolled for violin course in the same institute.
Identify all the objects & Similar Objects / Class or Type that defines the objects
IETE

Java Objects & Class Contd.


OBJECTS are:
Mr. White Faculty Mrs. White Faculty John Student Janet Student

Nano Car OOSE Course

Philosophy Department Violin Course

CS Department

All-Smart Institute

IETE

Properties of Object Orientated Programming (OOP) Common properties of OOP is given below-

Abstraction Encapsulation. Inheritance. Polymorphism.

IETE

Java as Object Orientated Programming


Java Source Code(.java file) Java Compiler (javac)
Bytecode (.class file)

Interpreter

Interpreter

Interpreter

JVM
Windows

JVM
Unix

JVM
Mac

Executable file(Output)
IETE

Example Java program to print HELLO WORLD

class exampleHW { public static void main (String args[]) { System.out.println (HELLO WORLD ); } }

IETE

Java Programming Elements


Contd.

Datatype byte short int long float double

Size 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits

Character takes 16 bits(Unicode), and size of the Boolean data type is machine dependent.
IETE

Java Programming Elements


Contd.
Arrays An Array is a Container object that holds a fixed number of values of a single type. Array can contain both primitive and reference data types. Each item in an array is called an element, and each element is accessed by its numerical index.
Array Declaration int myIntegers[ ]; Indicates the same int[ ] myIntegers; Array memory allocation: int myIntegers[] = new int[10]; Array Initialization: int myIntegers[] = {1,2,3,4,5};
IETE

Method Overloading
The Java programming supports language overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists. Method Overloading (Compile time Polymorphism) Two or more methods with different signatures. The functions which differ only in their return types cannot be overloaded. The compiler will select the right function depending on the type of parameters passed.
IETE

Method Overloading
Contd.
Example
Class ExampleMO { int method1 (int a) { } int method1 (int a, int b) // overloaded method method1 { } } IETE

Java Inheritance
Bicycle is-a relationships

M ountain Racing Tandem Bikes Bikes Bikes

class Mountain_Bike extends Bicycle { }


By the same way Racing_Bike & Tandem_Bike also extends Bicycle.
IETE

Method Overriding
Method Overriding (Runtime Polymorphism) A method in the subclass to override the method in super class that has the same signature. Which method to be called, is determined at runtime, not at the compile time. We used method overriding to achieve polymorphism. Example:
public class Animal { public static void testClassMethod() { System.out.println("The class method in Animal."); } public void testInstanceMethod() { System.out.println("The instance method in Animal."); } IETE }

The second class, a subclass of Animal, is called Cat: public class Cat extends Animal { public void testClassMethod() { System.out.println("The class method in Cat."); } public void testInstanceMethod() { System.out.println("The instance method in Cat."); } public static void main(String [] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); } } The output from this program is as follows: The class method in Animal. IETE The instance method in Cat.

Abstract Classes
An Abstract class is a conceptual class. An Abstract class cannot be instantiated objects cannot be created.Abstract classes provides a common root for a group of classes, nicely tied together in a package. When a class contains one or more abstract methods, it should be declared as abstract class. The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods.
IETE

Abstract Class -Example


Shape is a abstract class.
Shape

Circle

Rectangle

IETE

20

Abstract Class Example Contd.


public abstract class Shape { public abstract double area(); public void move() { // non-abstract method // implementation } } //The abstract methods needs to be get override in the corresponding sub classes.
IETE

Abstract Class Example Contd.


public Circle extends Shape { protected double r; protected static final double PI =3.1415926535; public Circle() { r = 1.0; ) public double area() { return PI * r * r; } } public Rectangle extends Shape { protected double w, h; public Rectangle() { w = 0.0; h=0.0; } public double area() { return w * h; } }
IETE

Interfaces
Interface is a conceptual entity similar to a Abstract class. Can contain only constants (final variables) and abstract method (no implementation) - Different from Abstract classes. Use when a number of classes share a common interface. Each class should implement the interface.

IETE

Interface - Example
<<Interface>> Speaker speak()

Politician speak()

Priest speak()

Lecturer speak()

IETE

Interfaces Definition
interface InterfaceName { // Constant/Final Variable Declaration // Abstract Methods } Example:interface Speaker { public void speak( ); }
Implementing Interface:class ClassName implements InterfaceName [, InterfaceName2, ] { // Body of Class }
IETE

Implementing Interfaces Example class Politician implements Speaker {


public void speak(){ System.out.println(Talk politics); } }

class Priest implements Speaker { public void speak(){ System.out.println(Religious Talks); } }


class Lecturer implements Speaker { public void speak(){ System.out.println(Talks Object Oriented Design and Programming!); } }

IETE

Java Packages
A package is a grouping of related types providing access protection and name space management. The types that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (input and output) are in java.io, and so on. You can put your types in packages too.

IETE

Java Packages
Example: package points; import java.util.*; class Point { int x, y; PointColor color; Point next; static int nPoints; } class PointColor { Point first; PointColor(int color) { this.color = color; } private int color; }

Contd.

// coordinates // color of this point // next point with this color

// first point with this color

// color components
IETE

String
Sequence of character. Example: Java, Smith.. In Java Strings are objects of String class. String objects can be created in ways:
String name= new String(Smith); String name= Smith;

IETE

String
String name=new String(Smith); String name1=new String(Smith); Stack

Contd.

Heap
Smith Smith

name name1

String name=Smith; String name1=Smith; Stack

Heap
Smith
IETE

name name1

String
String name=Smith; name=name+ Ray;
Stack

Contd.

String objects are immutable.

Heap

name

Smith

Smith Ray

??
IETE

Empty Strings
An empty String has no characters. Its length is 0.
String word1 = ""; String word2 = new String();

Empty strings

Not the same as an uninitialized String.


private String errorMsg;
errorMsg is null

IETE

Important Methods of String Class


charAt() Returns the character located at the specified index. concat() Appends one String to the end of another ( "+" also works). equalsIgnoreCase() Determines the equality of two Strings, ignoring case. length() Returns the number of characters in a String. replace() Replaces occurrences of a character with a new character. substring() Returns a part of a String. toLowerCase() Returns a String with uppercase characters converted. toString() Returns the value of a String. toUpperCase() Returns a String with lowercase characters converted. trim() Removes whitespace from the ends of a String.

IETE

Methods Equality
boolean b = word1.equals(word2); returns true if the string word1 is equal to word2

boolean b = word1.equalsIgnoreCase(word2); returns true if the string word1 matches word2, case-blind
b = Raiders.equals(Raiders);//true b = Raiders.equals(raiders);//false b = Raiders.equalsIgnoreCase(raiders);//true if(team.equalsIgnoreCase(raiders)) System.out.println(Go You + team);
IETE

Exceptions Exception Hierarchy


Throwable

Error

Exception

Checked Exception

Unchecked Exception

IETE

What do you do when an Exception


occurs?

Exceptions Handling exceptions


Handle the exception using try/catch/finally Throw the Exception back to the calling method.
public class MyClass { public void exceptionMethod() { try { // exception-block } catch (Exception ex) { // handle exception } finally { //clean-up } } IETE }

Try/catch/finally

Exceptions Handling exceptions Contd


Try/catch/finally - 2
public class MyClass { public void exceptionMethod() { try { // exception-block } catch (FileNotFoundException ex) { // handle exception } catch (Exception ex) { // handle exception } finally { //clean-up } } }

Using throws
public class MyClass { public void exceptionMethod() throws Exception { // exception-block } }
IETE

Exceptions Handling exceptions Contd.


Using throw
class MyException extends Exception { }
class TestEx { void doStuff() { throw new MyException(); // Throw a checked exception } }

IETE

Wrapper Class
Wrapper classes encapsulate, or wrap, the primitive types within a class. Thus, they are commonly referred to as type wrappers. Wrapper objects are immutable.

IETE

Wrapper Class Examples


int x=10; Integer i=new Integer(x); int y=i.intValue(); int dim=Integer.parseInt(args[0]);

IETE

Collections - Introduction
String student1 = a; String student2 = b; String student3 = c; String student4 = d; String student5 = e; String student6 = f;

Difficult to maintain multiple items of same type as different variables Data-manipulation issues Unnecessary code

IETE

Collections Arrays v/s Collections


abc def ghi jkl

Arrays

abc

123

new Person()

def

Collections

IETE

Collections - Overview

LinkedHashSet

IETE

Collections Collection types

Three basic flavors of collections: Lists - Lists of things (classes that implement List) Sets - Unique things (classes that implement Set) Maps - Things with a unique ID (classes that implement Map)

The sub-flavors: Ordered - You can iterate through the collection in a specific order. Sorted - Collection is sorted in the natural order (alphabetical for Strings). Unordered Unsorted

IETE

Collections Lists

ArrayList
Resizable-array implementation of the List interface. Ordered collection. Should be considered when there is more of data retrieval than Often used methods add(), get(), remove(), set(), size()

add/delete.

Vector
Ordered collection To be considered when thread safety is a concern. Often used methods add(), remove(), set(), get(), size()

Linked List
Ordered collection. Faster insertion/deletion and slower retrieval when compared to ArrayList

IETE

Collections Set

HashSet
Not Sorted Not Ordered Should be used if only requirement is uniqueness Often used methods add(), contains(), remove(), size()

LinkedHashSet

Not Sorted Ordered Subclass of HashSet Should be used if the order of elements is important

TreeSet
Sorted Ordered Should be used if you want to store objects in a sorted fashion Often used methods first(), last(), add(), addAll(), subset()
IETE

Collections Map

HashMap
Not Sorted, not ordered Can have one null key and any number of null values Not thread-safe Often used methods get(), put(), containsKey(), keySet()

Hashtable

Not Sorted, not ordered Cannot have null keys or values Thread-safe

LinkedHashMap
Not sorted, but ordered

TreeMap
Sorted, ordered

IETE

IETE

Anda mungkin juga menyukai