Você está na página 1de 84

More On Java

CS4280 Advanced Internet Applications Development

More on Java

Contents
Encapsulation and Information Hiding Constructors and Finalizers Abstract class, Interface and Inheritance Polymorphism Overloading, Dynamic Binding Package in Java Exceptions

More on Java

Encapsulation and Information Hiding


OOP encapsulates data and method into objects. A system / program is a collection of objects to perform special task Objects communicate with one another across well-defined interfaces.

More on Java

Encapsulation and Information Hiding


In Java, the unit of programming is the class (Object is an instance of a class) OOP programmer concentrate on creating their own user-defined type called classes (Also referred as programmer-defined types) Class contains data and the set of methods that manipulate the data

More on Java

Encapsulation and Information Hiding

More on Java

Information Hiding
Classes normally hide their implementation details from the clients of the classes Using Set and Get methods
public class Time1{ private int hour; public void setHour(int h){ hour=h; } public int getHour(){ return hour; } }

Private instance variables can be manipulated only by methods of the class


More on Java 6

Object-Oriented Programming in Java


Similarities with C++ User-defined classes can be used the same way as built-in types. Basic syntax Differences from C++ Methods (member functions) are the only function type Object is the topmost ancestor for all classes All methods use the run-time, not compile-time, types (i.e. all Java methods are like C++ virtual functions) The types of all objects are known at run-time Single inheritance only

More on Java

Object-Oriented Nomenclature
Class means a category of things
A class name can be used in Java as the type of a field or local variable or as the return type of a function (method)

Object means a particular item that belongs to a class


Also called an instance

For example, consider the following line:


String s1 = "Hello"; Here, String is the class, and the variable s1 and the value "Hello" are objects (or instances of the String class)

More on Java

Abstract Data Type


The concept of data abstraction is that the client of an class does not need to know how the class is implemented but only the rule of access (what will be done rather than how it will be done) Java classes defined abstract data types (ADTs) I.e. The primary activity in Java is creating new data types (classes) and expressing the interactions among objects of those data types

More on Java

Abstract Data Type


ADTs improved the program development process by providing an additional formalization. However, it does not replace structured programming In fact, all data types (built-in: int, float / user defined: Time1) are only approximations or models of real-world concepts and behaviors (Mathematical integers has infinitive value while data type int only have 32 bits in size). Therefore, it already is an abstract data type ADT actually captures two notions: data representation and the operations that are allowed on that data.

More on Java

10

Object Creation
Object is an instance of class

More on Java

11

Object Creation Java Example


ObjectReference = new className(Constructor Parameters) E.g
public String s; //declare an object reference with String type s=new String (Hello World); //Create the object

When an object is created, the constructor will be called

More on Java

12

Objects and References


Once a class is defined, you can easily declare a variable (object reference) of the class
Ship s1, s2; Point start; Color blue;

Object references are initially null


The null value is a distinct type in Java and should not be considered equal to zero A primitive data type cannot be cast to an object (use wrapper classes)

The new operator is required to explicitly create the object that is referenced
ClassName variableName = new ClassName();

More on Java

13

Constructors and Finalizers


Constructors
Invoked automatically each time an object of the class is instantiated (created) Is a method with the same name as the class Cannot specify return types or return values, otherwise the default constructor will be called A class may contain overloaded constructors (more than one) to provide a variety of means for initializing objects of that class

More on Java

14

Constructors and Finalizers

More on Java

15

Constructors and Finalizers


Time1 t1, t2; t1 = new Time1(); t2 = new Time1(10,20,0);
// call the first constructors // public t1(){.} //call the second constructors // public Time1(int h, int m, int s)

More on Java

16

Default Constructor
Compiler creates a default constructor that takes no arguments (noargument constructor) if no constructor is defined for the class The default constructor calls the default constructor of its parent class and then initialize the instance variables according the following rules:
Primitive numeric data type -> 0 Booleans ->false Object references->null

More on Java

17

Finalizers
System Resources, such as memory, may be acquired by an object when it was created Class in Java can have a finalizer method to return resources to the system It is guaranteed to be called to perform termination housekeeping on the object just before the garbage collector reclaims the memory for the object Always has the name finalize, receive no parameters and takes no arguments.

More on Java

18

Finalizers
Public class Employee extends Object{ private String firstName; private String lastName; private static int count; public Employee (String fName, String lName){ firstName=fName lastName=lName; ++count; //increment static count of employees } protected void finalize(){ --count; // decrement static count of employees } }

More on Java

19

Static Modifier
It indicates that the variables is shared by the entire class It can be accessed by the classname instead of just by an instance If a class Foo had a static variable bar foo1 = new Foo(); foo2=new Foo(); Foo.bar, foo1.bar, foo2.bar are all the same shared variables Similar example is Math.cos

More on Java

20

Abstract Classes
Idea Abstract classes permit declaration of classes that define only part of an implementation, leaving the subclasses to provide the details A class is considered abstract if at least one method in the class has no implementation An abstract method has no implementation (known in C++ as a pure virtual function) Any class with an abstract method must be declared abstract If the subclass overrides all the abstract methods in the superclass, than an object of the subclass can be instantiated An abstract class can contain instance variables and methods that are fully implemented Any subclass can override a concrete method inherited from the superclass and declare the method abstract

More on Java

21

Abstract Classes
An abstract class cannot be instantiated, however references to an abstract class can be declared
public abstract ThreeDShape { public abstract void drawShape(Graphics g); public abstract void resize(double scale); }

ThreeDShape s1; ThreeDShape[] arrayOfShapes = new ThreeDShape[20];

Classes from which objects can be instantiated are called concrete classes

More on Java

22

Abstract Class
Only abstract classes may have abstract methods
methods that are declared but not yet implemented. abstract class Point { int x = 1, y = 1; void move(int dx, int dy) { x += dx; y += dy; alert(); } abstract void alert(); }

More on Java

23

Abstract Class
It is generally used as superclass in inheritance We can also refer them to abstract superclass The sole purpose of abstract class is to provide an appropriate superclass from which other class may inherit interface and/or implementation Classes from which objects can be instantiated are called concrete class

More on Java

24

Abstract Classes
It acts as a parent of other class but cannot be directly instantiated It can provide some common behavior in the class The class does not have enough information to be used by itself Java lets you declare a class abstract and the compiler will not let you build an instance of it

More on Java

25

Abstract Class, Interface and Inheritance


An abstract class cannot be instantiated
Point p=new Point(); // compile-time error

A subclass of an abstract class that is not itself abstract may be instantiated


class SimplePoint extends Point { void alert() { } } Point p = new SimplePoint();

//Correct!

A class type should be declared abstract only if the intent is that subclasses can be created to complete the implementation
More on Java 26

Example Shape.java
// This appears in Core Web Programming from Prentice Hall Publishers, and may be freely // used or adapted. 1997 Marty Hall, hall@apl.jhu.edu. /** The parent class for all closed, open, curved, * and straight-edged shapes. */ public abstract class Shape { protected int x, y; public int getX() { return(x); } public void setX(int x) { this.x = x; } public int getY() { return(y); } public void setY(int y) { this.y = y; } }
More on Java 27

Abstract Curve.java and StraightEdgeShape.java


public abstract class Curve extends Shape { public Curve() { // CONSTRUCTOR implementation not available }} public abstract class StraightEdgedShape extends Shape { public StraightEdgedShape() { // CONSTRUCTOR implementation not available }} you can extend Curve to create a circle and have circle to have a method to calculate its area Then the circle class will have no abstract and include a getArea method

More on Java

28

/** A circle extends from Curve. * */ public class Circle extends Curve { private double radius; public Circle(int x, int y, double radius) { setX(x); setY(y); setRadius(radius); getRadius() } public double getRadius() { return(radius); } public void setRadius(double radius) { this.radius = radius; } }

More on Java

29

Java Interface
Borrowed from the Objective-C protocol Used to identify a common set of methods for the group of classes that implement the interface Also used to share constant between classes. Provide the benefits of multiple inheritance without its implementation difficulties. Provide a Standard framework for accessing classes

More on Java

30

Interfaces
Idea Interfaces define a Java type consisting purely of constants and abstract methods An interface does not implement any of the methods, but imposes a design structure on any class that uses the interface A class that implements an interface must either provide definitions for all methods or declare itself abstract

More on Java

31

Interfaces
Modifiers All methods in an interface are implicitly abstract and the keyword abstract is not required in a method declaration Data fields in an interface are implicitly static final (constants) All methods in an interface are implicitly public

public interface Interface1 { DataType CONSTANT1 = value1; DataType CONSTANT2 = value2; ReturnType1 method1(ArgType1 arg); ReturnType2 method2(ArgType2 arg); }
More on Java 32

Declaring
InterfaceModifiers interface interfaceName E.g. public interface Clickable{ int x=0, y=0; void click(); void doubleClick(); } ExtendsClause InterfaceBody

InterfaceModifiers could be abstract(default) and public Like class declaration, only one interface may be declared public in a given compilation unit(program file) All variables declared in an interface body are assumed to be both static and final All methods declared in an interface body are assumed to be abstract and do not have method bodies Only access methods can be declared (no constructor / finializier)

More on Java

33

Interfaces
Extending Interfaces
Interfaces can extend other interfaces, which brings rise to subinterfaces and super-interfaces Unlike classes, however, an interface can extend more than one interface at a time
public interface Displayable extends Drawable, Printable {

// Additonal constants and abstract methods ... }

Implementing Multiple Interfaces


Interfaces provide a form of multiple inheritance because a class can implement more than one interface at a time
public class Circle extends TwoDShape implements Drawable, Printable { ... }

More on Java

34

Implementing Interfaces
To implement an Interface, use the keyword implements to introduce an implement clause of the class declaration.
E.g.
public class MyButton implements Clickable{ . //Implementation of interface Clickable public void Click(){ . } //Implementation of interface Clickable public void doubleClick(){ . } }

More on Java

35

Interface
An interface may have many methods. If a class implements an interface, but only implements some of its methods, then this class becomes an abstract method. It cannot be instantiated.

More on Java

36

Implementing Interfaces

More on Java

37

Implementing Interfaces
An interface reference (variable whose declared type is an interface) may refer to any instance of a class which implements the specified interface. E.g.
public Clickable clickedObj; clickedObj=new MyButton(); clickedObj=new MyIcon(); clickedObj=new MyScrollBar();

For a class that implement the interface, all the abstract methods must be declared in order to implement either by the class itself or one of its superclasses. Otherwise, the class is not implementing the interface.

More on Java

38

Benefits of Interfaces
Allow standard sets of methods to be used across the class hierarchy. I.e. Interface defines the method signature (name of method , type and number of parameters it received) for all class that support those functionality. Therefore, it establishes a uniform approach to implementing these common operation
e.g.
public interface MouseMotionListener{ public void mouseMove(int x, int y);
// All implementing classes receive mouse move event // with the x, y coordination of the mouse pointer

public void mouseDrag(int x, int y);


// All implementing classes receive mouse drag event // with the x, y coordination of the mouse pointer

More on Java

39

Benefits of Interfaces
Allow object to be referenced by the methods they support without considering the actual object being implemented (Dynamic binding- The decision as to what method to invoke is deferred until execution time) Considering the following method:

More on Java

40

Benefits of Interfaces
activeObject can be accessed according the method signatures defined in Interface Clickable e.g. activeObject.click();
/*ActiveObject may be an reference of MyButton/ My Icon / MyScrollbar but the caller need not be awaked of it */

More on Java

41

Inheritance
Inheritance is a form of software reusability New classes (subclass) are created (inherit) from existing classes (superclass) by absorbing their attributes and behaviors Saves time in program development Java only supports single inheritance. I.e. a class is derived from one superclass. To derived from an existing class, use the keyword extends following by superclasss name

More on Java

42

Inheritance - Example
//Superclass// public class Point{ protected int x, y; // coordinates of the Point public Point(){ setPoint(0,0) } public Point(int a, int b){ setPoint(a,b); } public void setPoint(int a, int b){ x=a;y=b; } public int getX() {return x;} public int getY() {return y;} } //Subclass// public class Circle extends Point{ protected double radius; public Circle(){ setRadius(0); } public Circle(double r, int a, int b){ super(a,b); setRadius( r); } public void setRadius(double r){ radius=(r>0.0?r:0.0); } public void getRadius(){ return radius; } }
More on Java 43

Inheritance - Constructor
Java automatically calls superclasss default constructor(noargument constructor) by default
public Circle(){ setRadius(0); } } public Circle(){ super(); setRadius(0);

It is a compiling error If no default constructor can be found in the superclass The keyword super is used for calling the superclasss constructor

More on Java

44

Inheritance - Constructor
The call to the superclass constructor must be the first line in the body of the subclass constructor To call the superclass constructor other than default constructor, using the superclass constructor call syntax[I.e. keyword super followed by a set of parenthese containing the arguments to the superclass constructor. E.g. use super (a,b); in the constructor of circle will call the constructor point(int a, int b) in the class Point

More on Java

45

Inheritance - Finalizer
Java will not call the finalizer of superclass If you have defined the finalizer in your subclass, You should call the superclass finalizer at last E.g.
protected void finalize(){ // finalizer of circle. // calling the superclasss finalizer super.finalize(); }

More on Java

46

Multiple Inheritance - Interface


Extends only define a subclass, thus, only one parent class Class does not support multiple inheritance Interface can be extends from more than one interface
public interface Icon extends Clickable, Movable{ // Clickable and Moveable are Java interface type .. .. }

Class that implements the interface Icon must declare all the functions defined in Clickable and moveable as well as those in Icon

More on Java

47

Multiple Inheritance - Interface


public interface Movable { void moveTo(int x, int y); //move to coordination x,y int getX(); // get the x-coordination of the object int getY(); // get the y-coordination of the object } public interface Icon extends Clickable, Movable{ String getFileName(); // get the filename of the icon }

More on Java

48

Multiple Inheritance - Interface


public class MyIcon implements Icon{ public void click(){ . // Clickables implementation } public void doubleClicke(){ // Clickables implementation } public void moveTo(int x,int y){ // Movables implementation } public int getX(){ // Movables implementation } public int getY(){ // Movables implementation } public String getFileName(){ // Icon s implementation } }

More on Java

49

Differences Abstract Class and Interface


In an interface, the data must be constants; an abstract class can have all types of data Each method in an interface has only a signature without implementation; an abstract class can have concrete methods No abstract modifier appears in an interface, you must put the abstract modifier before an abstract method in an abstract class

More on Java

50

Implicit Subclass-Object-to-Superclass Object Conversion


Subclass object is a superclass object. I.e. subclass objects can be treated as superclass objects Point p=new Circle(); Superclass objects cannot be assigned to a subclass reference Circle c=new Point(); //compiling error

More on Java

51

Implicit Subclass-Object-to-Superclass Object Conversion


Referring to a superclass object with a superclass reference is straightforward
Point p=new Point();

Referring to a subclass object with a subclass reference is straightforward


Circle c=new Circle();

Referring to a subclass object with a superclass reference is safe because the sub class object is an object of it its superclass as well. (Only refer to superclass members
Point p=new Circle(); p.setPoint(1,2); p.setRadius(2); // superclass member // syntax error

Referring to a superclass object with a subclass reference is a syntax error Circle c =new Point();

More on Java

52

Polymorphism
Polymorphism refers to the ability of objects to have many methods of the same name but with different forms The compiler and runtime system matching each method invocation to the correct method, class, and object Compiler achieve polymorphism by method overloading Runtime system achieve polymorphism by dynamic binding

More on Java

53

Overloading
Methods with same name but different signatures (parameters list) are said to be overloaded The overloaded methods must either
Both declared in the same class Both inherited by a class One declared and one inherited

return types or throws clauses of two overloading methods could be different or same.

More on Java

54

Overloading
The following method is for the class Point
public void setPoint(int a, int b){ x=a;y=b;} public void setPoint(Point p){
x=p.getX(); y=p.getY();

// method 1 // method 2

When the method setPoint is called, the compiler will determine which method should be invocated based on the parameters the caller supplied
setPoint(1,2); //method 1 will be called setPoint(new Point(12,14)); //method 2 will be called setPoint(p1); //p1 is an object of point. Method 2 will be called

More on Java

55

Overloading
Another method (method 3) is added to class Circle
public void setPoint(Circle c){
x=c.getX(); y=c.getY();

More on Java

56

Dynamic (Method) Binding


the capability to defer the decision of method invocation until runtime.
I.e. The actual method and the corresponding object /class to be invocated may not be known at the time of compilation.

More on Java

57

Dynamic Binding - Java Dynamic binding in Java is achieved by superclass reference and Interface type When an object reference is obtained as method parameter, the actual implementation is determined at run time
E.g. public void setPoint(Point p){ // The reference of p can be an object of class Point /Circle }

When an object reference type is an interface type, the actual implementation is determined at run time
E.g. public void objectClicked(Clickable activeObject){ // The implementation of activeObject is supplied // by the caller }

More on Java

58

Package in Java
In java, related classes and interfaces can be stored in a same directory to form a package

More on Java

59

Package in Java
Package defines the relationship among classes and interfaces and its location I.e. Related class can be found at same directory (folder) It also help to resolve name conflict among class and interface
E.g. Class Point has also defined in the package awt of Java Standard Library2 SDK. If both are imported into a compilation unit, package name is used to resolve the ambiguity java.awt.Point javaPoint; // Point class defined in java MyLib.Graphic.Point myPoint; //Point class defined in myLib

More on Java

60

Package in Java
To import a class / package in the compilation unit, use Import <packageName.className>

More on Java

61

Creating Package
To create package in Java, use the package statement with package name package MyPackage; public class ClassA{ protected String content; public String toString(){ return I am Class A, from MyPackage :+content; } }

More on Java

62

Creating Package
To place the package under given root directory use tag -d while compiling the class
javac -d <root directory> programFile.java e.g. javac -d c:\temp ClassA.java (make sure the directory c:\temp do exist)

More on Java

63

Creating Package
package MyLib.Graphic; public class Point{ . } javac -d c:\temp Point.java package MyLib.Graphic; public class Line{ . } javac -d c:\temp Line.java
More on Java 64

Creating Package
To access the class within a given package, use the keyword import in the source file import MyLib.ClassA;
public class TestPackage{ public static void main(String[] args){ ClassA a=new ClassA(); System.out.println(a); } }

To compile the the class


javac -classpath c:\Mylib TestPackage.java

To execute the program


java -classpath c:\Mylib; TestPackage

More on Java

65

What is an Exception ?
Is an event that disrupts the normal flow of instructions during the execution of a program. When an error occurs within a method, the method creates an object and hands it off to the runtime system Exception objects inherit from the Throwable class

More on Java

66

Exception ?
The exception object contains an information about the error including its type and state of the program Creating an exception object and handing it to the Runtime system is called throwing an exception After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible something to handle the exception is the ordered list of methods that has been called to get to the method where the error occurred The code that handles the error is called exception handler

More on Java

67

Exception Handling
In Java, exception will be thrown when semantic constraints are violated and will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred.

More on Java

68

Exception Handling
- Program without exception handling -

// sample code int x=0; int z=1/x; z++;

More on Java

69

Exception Handling
- Program with Exception Handling // sample code try{ int x=0; int z=1/x; z++; }catch (ArithmeticException e){ System.out.print(Except.); z=0; } System.out.println(value of z+z); z++;

More on Java

70

Exception Handling
Compare with exception handling with C++
Exception-handling construct (try/catch) has a finally clause that always get executed, regardless of whether or not an exception was thrown You can require users of your methods to handle exceptions your method generate. Otherwise, the code will not compile

More on Java

71

Exception Handling
Basic Form
Try{ statement1; statement2; }catch (SomeException someVar){ handleTheException(someVar); }

More on Java

72

Exception Handling
A single try can have more than one catch. Try{ }catch(Exception1 e1){ }catch(Exception2 e2){ }catch(ExceptionN eN){ } If an exception is generated, Java executes the first catch clause that matches the type of exception thrown. Therefore, in general, a more specific exception type should be catch before a more general ones. Otherwise, syntax error occurs.

More on Java

73

Exception Handling
Try{ urlString=in.readLine(); url=new URL(urlString); }catch (MalformedURLException mue){ getURL(); }catch (IOException ioe){ return (null); } Since MalformedURLException is a subclass of IOException, therefore it should be catch first.

More on Java

74

Exception Handling
The finally clause that always get executed, regardless of whether or not exceptions are thrown. It is executed even if break, continue, or return is used within the try or catch clause.
Try{ urlString=in.readLine(); url=new URL(urlString); }catch (MalformedURLException mue){ System.out.println(URL erro); }catch (IOException ioe){ return (null); }finally{ System.out.println(I am finally); }

More on Java

75

Exception Handling
public class Test{ public static int functionA(){ try{ int y; y=1/0; }catch(ArithmeticException ae){ System.out.println("ArithmeticException catch: "+ae); return 1; }finally{ System.out.println("I am finally"); } return 0; } //end functionA public static void main(String args[]){ int z=functionA(); System.out.println("Function A return:"+z); } //end main } //end class
More on Java 76

Exception Handling
Result:
>ArithmeticException catch: java.lang.ArithmeticException: / by zero >I am finally >Function A return:1

More on Java

77

Exception Handling
try{ int x; x=1/0; }catch(NumberFormatException nfe){ System.out.println( Number format exception+nfe); }catch(ArithmeticException ae){ System.out.println(Arithms Exception: +ae); }

More on Java

78

Exception Handling
try{ MyObject x=null; x.myFunctionA(); //NullPointerException will be

thrown

}catch(NumberFormatException nfe){ System.out.println( Number format exception+nfe); }catch(ArithmeticException ae){ System.out.println(Arithms Exception: +ae); }

More on Java

79

Exception Handling - Define an Exception A customized exception can be make by subclassing any of the existing exception type

E.g.
public class MyException extends Exception{ public MyException(){ super(My exception throw); } public MyException(String message){ super(message); } }

More on Java

80

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

// Fig. 14.1: DivideByZeroException.java // Definition of class DivideByZeroException. // Used to throw an exception when a // divide-by-zero is attempted. public class DivideByZeroException extends ArithmeticException { public DivideByZeroException() { super( "Attempted to divide by zero" ); } public DivideByZeroException( String message ) { super( message ); }

Define our own exception class (exceptions are thrown objects). Default constructor (default message) and customizable message constructor.

16 } 17

Class DivideByZero Exception (extends Arithmetic Exception)


More on Java 81

Exception Handling
- Throwing Exception For a method that potentially generates one or more exceptions that will not handle explicitly, it should declared using throws construct as follow
public returnType Method () throws someException{ } public returnType Method () throws exception1, exception 2,exception3{ }

More on Java

82

Exception Handling
- Throwing Exception To generate an exception, use the throw construct as follow
{ throw new IOException(); //Exception will be thrown at this point }

More on Java

83

Example
// Definition of method quotient. Used to demonstrate // throwing an exception when a divide-by-zero error // is encountered.Fig.14.1 in book Dietel & Dietel // catch it later public double quotient( int numerator, int denominator ) throws DivideByZeroException { if ( denominator == 0 ) throw new DivideByZeroException(); return ( double ) numerator / denominator; }

More on Java

84

Você também pode gostar