Java Review 3 Rem Collier. Java Wrapper Classes In Java, the term wrapper class commonly refers to a set of Java classes that “objectify” the primitive.

Slides:



Advertisements
Similar presentations
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Advertisements

Java Review Interface, Casting, Generics, Iterator.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Written by: Dr. JJ Shepherd
04 - Abstract Classes and Interfaces. 2 © S. Uchitel, 2004 Abstract Classes Unlike classes, these cannot be instantiated. Unlike classes, these cannot.
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
OBJECT-ORIENTED PROGRAMMING. What is an “object”? Abstract entity that contains data and actions Attributes (characteristics) and methods (functions)
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
Java Review 2. The Agenda The following topics were highlighted to me as issues: –File IO (Rem) –Wrappers (Rem) –Interfaces (Rem) –Asymptotic Notation.
Abstract Classes and Interfaces
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
MIT AITI 2003 Lecture 7 Class and Object - Part I.
Io package as Java’s basic I/O system continue’d.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
CSC3170 Introduction to Database Systems
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
SOFTWARE TECHNOLOGY - I CONSTANTS VARIABLES DATA TYPES.
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
The Java Programming Language
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Data Structures and Java CS 105. L7: Java Slide 2 Data structure Data structure defined: A systematic way of organizing and accessing data Examples Dictionary:
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
1 Even even more on being classy Aaron Bloomfield CS 101-E Chapter 4+
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Fall 2015CISC124 - Prof. McLeod1 CISC124 Have you filled out the lab section survey? (As of last night 54 left to fill out the survey.) TA names have been.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
State Design Pattern. Behavioral Pattern Allows object to alter its behavior when internal state changes Uses Polymorphism to define different behaviors.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Written by: Dr. JJ Shepherd
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
OOP Basics Classes & Methods (c) IDMS/SQL News
Object Oriented Programming Object and Classes Lecture 3 MBY.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
April 13, 1998CS102-02Lecture 3-1 Data Types in Java CS Lecture 3-1 Java’s Central Casting.
Topic: Classes and Objects
Sixth Lecture ArrayList Abstract Class and Interface
Objects, Classes, Program Constructs
Chapter 8: Collections: Arrays
More inheritance, Abstract Classes and Interfaces
Units with – James tedder
Object-Oriented Programming
Chap 2. Identifiers, Keywords, and Types
CMSC 202 Exceptions.
Presentation transcript:

Java Review 3 Rem Collier

Java Wrapper Classes In Java, the term wrapper class commonly refers to a set of Java classes that “objectify” the primitive Java types. –That is, for each primitive type, there is a corresponding Java “Wrapper” class that represents that type. –e.g. the wrapper for the int type is the Integer class. Wrapper Classes are based upon the well-known software engineering design pattern called the Wrapper pattern. –A design pattern is a template solution to a common problem. It describes the problem and identifies the recommended solution(s) to that problem. –Because design patterns deal with common problems, they are often quite abstract!

Wrapper Design Pattern –Some code (the client) needs a class to use a certain interface (which it does not use). The problem: –e.g. we want to store an int in a Vector, but Vectors do not accept primitive types. The Solution: –We create another class that wraps the underlying class/type and provides an appropriate interface for the client. –e.g. we create an Integer class that subclasses Object (as all classes do), allowing us to store wrapped int’s in Vectors.

Example that will not work import java.util.Vector; public class MyApp { public static void main(String[] args) { int myValue = 2; Vector myVector = new Vector(); myVector.addElement(myValue); for (int x=0; x < myVector.size(); x++) { System.out.println(“Value: “ + myVector.get(x)); } The compiler detects an error here

Example that will work import java.util.Vector; public class MyApp { public static void main(String[] args) { int myValue = 2; Vector myVector = new Vector(); myVector.addElement(new Integer(myValue)); for (int x=0; x < myVector.size(); x++) { System.out.println(“Value: “ + myVector.get(x)); } Here we wrap the int in the Integer class

Java Wrapper Classes Object BooleanCharacterVoidNumberString ShortDoubleIntegerLongFloatByte

Some Useful Methods The Java Wrapper Classes include various useful methods: –Getting a value from a String e.g. int value = Integer.parseInt(“33”); sets value to 33. –Converting a value to a String: e.g. String str = Double.toString(33.34); sets str to the String “33.34”. –Getting a wrapper class instance for a value: e.g. Integer obj = Integer.getInteger(“12”); creates a new Integer object with value 12 and makes obj refer to that object.

Some Useful Methods –Getting the maximum permitted int value e.g. int value = Integer.MAX_VALUE; sets value to –Getting the minimum permitted int value e.g. int value = Integer.MIN_VALUE; sets value to –Getting the value in an Integer object e.g. int value = new Integer(545).intValue(); sets value to 545.

Reading a Double import java.io.*; class MyProgram { public static void main(String[] args) { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String line = null; System.out.println("Input Something:" ); try { line = in.readLine(); } catch (IOException ie) { System.out.println("Exception caught: " + ie); } try { double value = Double.parseDouble(line); System.out.println("Value: " + value); } catch (NumberFormatException nfe) { System.out.println("You didn't enter a double number"); }

Interfaces in Java In Object-Oriented terms, the interface of a class is the set of public methods and data members of that class. –These methods and data members describe how external code (I.e. other classes) can interact with the class. –Once a class is made publicly available for use, great care is required when changing that classes interface. E.g. consider how annoyed you would be if Sun changed the interface of the System class from System.out to System.cout… Java supports the definition of interfaces independent of implementation of that interface. –A Java interface is a named collection of method definitions (without implementation). An interface can also include constant declarations. –In Java, we define an interface using the interface keyword.

Example Interface Let us consider a general security service for web applications. –We don’t always know how we wish to validate users, so we cannot implement a general user validation algorithm. –So, we create an interface that describes what a security service should do, and leave it to the developer of a specific application to implement a particular security service. interface SecurityService { public boolean validateUser(String uid, String pwd); public static final String ADMIN_USERNAME = “Admin”; }

Interfaces in Java The definition of the methods described in a Java interface is the responsibility of any class that implements that interface. If a class implements an interface, then it must include definitions for all of the methods described in that interface. –If you do not include definitions for all the methods, the class will not compile! A powerful feature of Java interfaces is that they can be implemented in more than one class! –For example, our SecurityService interface could be implemented as: A DatabaseSecurityService, which looks validates the username and password against a database table, or A SimpleSecurityService, which validates the username and password against hardcoded values for the username and password.

Interface Example interface SecurityService { public boolean validateUser(String uid, String pwd); public static final String ADMIN_USERNAME = “Admin”; } class SimpleSecurityService implements SecurityService { public boolean validateUser(String uid, String pwd) { if (uid.equals(ADMIN_USERNAME) && pwd.equals(“god”)) { return true; } return false; }

Using Interfaces + Implementations Java interfaces can be used as types. –For example: SecurityService service; Variables or attributes whose type is an interface can be used to reference any class the implements that interface. –For example: SecurityService service = new SimpleSecurityService(); When an object is cast as an interface, only those methods declared in the interface may be accessed. –For example: boolean valid = service.validateUser(“rem”, “hi”);

A simple login program import java.io.*; class MyProgram { public static String readUserInput() { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); try { return in.readLine(); } catch (IOException ie) { System.out.println("Exception caught: " + ie); } return null; }

A simple login program public static void main(String[] args) { System.out.print(“Username:”); String username = readUserInput(); System.out.print(“Password:”); String password = readUserInput(); SecurityService service = new SimpleSecurityService(); if (service.validateUser(username, password)) { System.out.println(“Valid User”); } else { System.out.println(“Invalid User”); }

Some Comments… Another way in which we could have coded this example is through inheritance and abstract classes. class SecurityService { public abstract boolean validateUser(String uid, String pwd); public static final String ADMIN_USERNAME = “Admin”; } class SimpleSecurityService extends SecurityService { public boolean validateUser(String uid, String pwd) { if (uid.equals(ADMIN_USERNAME) && pwd.equals(“god”)) { return true; } return false; }

So, what is the need for interfaces? It is not always possible for us to use inheritance to deliver the required interface. –Remember: Java supports only single inheritance. That is, a class has exactly one parent class. Whilst a class can have only one parent class, it can implement many interfaces. –A class includes both private and public methods and attributes. –Java interfaces only define what methods must be implemented, not how to implement them! –So, we can write classes that subclass some parent class and implement one or more interfaces! –But when is this useful?

Another Example Lets consider an alarm clock service. –This service notifies objects after a certain amount of time has passed. –It is implemented through two components: An AlarmClock class that implements the service, and A Sleeper interface that classes wishing to use the service must implement. –Whenever an object wishes to sleep, it contacts an alarm clock instance requesting that it be allowed to sleep for a specified time. –Once that specified time has passed, the alarm clock tells the sleeping object to “wake up”.

The AlarmClock class import java.util.ArrayList; class AlarmClock { public static void letMeSleepFor(Sleeper sleeper, long time) { new AlarmThread(sleeper, time).start(); }

The AlarmThread class class AlarmThread extends Thread { private Sleeper sleeper; private long time; public AlarmThread(Sleeper sleeper, long time) { this.sleeper = sleeper; this.time = time; } public void run() { try { sleep(time); } catch (Exception e) { System.out.println(“Failed to sleep”); } sleeper.wakeUp(); }

The Sleeper interface interface Sleeper { public static final long ONE_MINUTE = 60000; public static final long ONE_SECOND = 1000; public void wakeUp(); } public class TestSleeper implements Sleeper { private int iterations; public TestSleeper() { iterations = 0; } public void wakeUp() { Iterations++; System.out.println("Woken up for the " + iterations + " time."); AlarmClock.letMeSleepFor(this, ONE_SECOND); }

The Applet POC So, what happens when we want an Applet to use this service? class ClockApplet extends Applet implements Sleeper { //... public void wakeUp() { repaint(); AlarmClock.letMeSleepFor(ONE_MINUTE); } //... } Obviously, we could not use inheritance here…