1 / 99

Java Workshop (Part 2)

Java Workshop (Part 2). John Lamertina January 2005. Java Workshop Content. Introduction Variables, Arrays, and Strings Operators, Conditions, and Loops Object-Oriented Programming Java Class Library Class Methods and Data Inheritance and Interfaces. Computer Systems are Complex.

neylan
Télécharger la présentation

Java Workshop (Part 2)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Workshop(Part 2) John Lamertina January 2005

  2. Java Workshop Content • Introduction • Variables, Arrays, and Strings • Operators, Conditions, and Loops • Object-Oriented Programming • Java Class Library • Class Methods and Data • Inheritance and Interfaces

  3. Computer Systems are Complex • Computer systems are complex packages of hardware & software that attempt to model the data and calculations of a “business” system • So complex that half of IT projects are abandoned before completion1 • The complexity is often compounded because of ineffective communication between the client (the “business”) and the IT developer 1. Standish Group Survey, 1996

  4. Objects Aid Understanding • We all know that an object is a person, place, or thing • Objects are natural to our human understanding of the world around us • We naturally differentiate objects by their attributes (e.g. size and color) • We naturally distinguish between whole objects and their component parts (e.g. an entire car vs. its doors, seats, and windows) • We naturally classify objects (e.g. tree vs. car)

  5. Object Oriented Programming offers: • Better communication by using the natural language of objects • business objects are well understood and explained by the client • business objects are translated directly to an object-oriented programming language (e.g. Java) • Improved efficiency • through reuse of existing object models • Raised reliability • using tested and proven building blocks (instead of re-inventing the wheel) • Reduced complexity • Abstraction allows “black-boxing”: separating how an object is used from how it is implemented

  6. Business Example:College Admissions Office • Business Objects: • Students • Admissions Counselors • Admissions Form • Acceptance Letter

  7. Foundation Principles of Object Oriented Programming • Encapsulation • Data and code bound together in one object • Polymorphism • One interface to access a general set of actions • Inheritance • An object acquires properties of another object

  8. Example: Vehicle Object Userinteracts (interfaces) with a vehicle (car, boat, truck, e.g.) via the interface (steering wheel, gauges, accelerator, brake) Mechanicsimplement a vehicle (e.g. car) by creating and assembling the engine, transmission, wheels, etc Abstraction: separate interaction (interface) from implementation. Encapsulation: hide details of the implementation.Polymorphism: common interface for each vehicleInheritance: car & boat inherit components of the vehicle class.

  9. Foundation Principle #1: Encapsulation • Data and code bound together in one object • Data and code protected from outside manipulation or misuse • Class defines the data and code that acts on the data • An object is an instance of the class • Data and code are called members of the class • Data are referred to as instance variables • Code blocks are referred to as methods

  10. Foundation Principle #2:Polymorphism • One interface to access a general set of actions • Example: a steering wheel is the interface which operates a car, a truck, or a boat. Although the actual steering mechanisms may be different behind each dash board, to the operator, the steering wheel acts essentially the same in all cases. • We can define a generic interface to a group of related actions, even if the actual implementation is somewhat different in each case. • Polymorphism helps reduce complexity by allowing the same interface to be applied for a general set of actions.

  11. Foundation Principle #3: Inheritance • An object acquires properties of another object • Hierarchical classification • Example #1: an apple and an orange are extensions of the fruit class. Fruit is food whose characteristics include juicy, sweet, etc. An apple has these characteristics and specific additional traits (grows on trees, edible skin, etc). • Inheritance allows an object to inherit traits of its parent. Thus one object can be a specific instance of a more general case. • Example #2: Vehicle is the parent class. Cars, trucks, planes, and boats are extensions of, and therefore inherit properties of the vehicle class.

  12. Class and Object • The Class is the essence of OOP in Java • A Class is a template that defines the form of an Object • Class specifies data and methods • Objects are instances of a class • A class is a logical abstraction; an object is a physical representation of the class and exists in memory

  13. Example Class: Vehicle class Vehicle { int passengers; // # passengers int fuelCap; // fuel capacity int mpg; // fuel consumption int static numVehicles = 0; } No special modifiers for instance data. static does not mean that value is unchanging. static means class-level. Special modifier for shared data: static

  14. Construct Objects Vehicle hisMiniVan = new Vehicle(); Vehicle hisCar = new Vehicle(); Vehicle hisTruck = new Vehicle(); Vehicle hisBoat = new Vehicle();

  15. Set Object Properties hisMiniVan.fuelCap = 16; hisMiniVan.passengers = 7; hisMiniVan.mpg = 21; Values assigned to a specific instance of the Vehicle class. Data name: mpg Dot operator links object to its data Object name: hisMinivan

  16. Set Property Shared by All Objects of the Class Vehicle.numVehicles++; Value assigned represents all objects of the Vehicle class. Shared (static) data name: numVehicles Class name instead of an instance name: Vehicle static does not mean that value is unchanging. static means class-level.

  17. Class Method class Vehicle { int passengers; // # passengers int fuelCap; // fuel capacity int mpg; // fuel consumption int static numVehicles = 0; int range() { return fuelCap * mpg; } } Look! No dot operators. Save class in file: Vehicle.java

  18. Test Vehicle Object class TestVehicle { public static void main(String[] args) { Vehicle herMiniVan = new Vehicle(); herMiniVan.passengers = 7; herMiniVan.fuelCap = 16; herMiniVan.mpg = 21; int eff = herMiniVan.efficiency(); int rng = herMiniVan.range(); System.out.println (“Efficiency is " + eff + " passenger miles per gallon"); System.out.println (“Range per tank of gas is “ + rng); } } Dot operator links object to methods Save class in file: TestVehicle.java

  19. Constructors • Constructor methods initialize an object when it is created • Constructor has same name as the class • Constructor has no return type • Multiple constructor methods are common • Using the principle of Method Overloading • Java creates a default constructor that assigns all instance data to zero • You may override the default constructor

  20. mpg refers to local parameter this.mpg refers to instance data Add Constructors to the Class // Constructor Methods Vehicle() { passengers = 4; fuelCap = 12; mpg = 24; } Vehicle(int p, int f, int mpg){ this.passengers = p; this.fuelCap = f; this.mpg = mpg; } Override the default constructor Constructor with parameters Vehicle is an overloaded method

  21. Method Overloading • Overloading is one form of Polymorphism • Overloaded methods have the same name, but different parameter profile (type, order, or number of parameters)

  22. Vehicle methods are Overloaded // Constructor Methods Vehicle() { ... } Vehicle(int p, int f, int mpg) { ... } Although method names are the same… … parameter profiles are different

  23. Test Vehicle Constructors ourCar gets new default values class TestVehicle { public static void main(String[] args) { Vehicle ourCar = new Vehicle(); Vehicle ourTruck = new Vehicle(2,20,16); int r1 = ourCar.range(); int r2 = ourTruck.range(); System.out.println (“Range per tank of gas is “ + r1 “ and “ + r2); } } ourTruck gets parameter values

  24. Private Data and Access Methods • Limit the ability of outside classes to access (set or get) an object’s data • Use the private modifier on instance data • Create specific Access Methods

  25. Add Access Methods (get & set) class Vehicle { private int passengers; // # passengers private int fuelCap; // fuel capacity private int mpg; // fuel consumption private int static numVehicles = 0; void setPassengers(int p) if ((p > 0) && (p < 15)) { this.passengers = p; else this.passengers = 2; } int getPassengers() { return passengers; } } private access modifier added set access method checks validity get access method returns value

  26. Access Shared (Static) Data with Static Methods class Vehicle { private int passengers; // # passengers private int fuelCap; // fuel capacity private int mpg; // fuel consumption private int static numVehicles = 0; public static int getNumVehicles() { return numVehicles; } } static method to access static data

  27. Some Points to Remember • Encapsulation, Polymorphism, and Inheritance • Class vs Object • static means class-level • Dot Operator • this refers to instance data within the class • Run with a test class containing main • Constructors initialize an object • Constructors may be Overloaded • Make instance data private and add access methods (get & set)

  28. Exercise (1) • Create the Vehicle and TestVehicle classes that were begun in this module • Include and use at least two Constructors • Include Access Methods for all instance data • Create several Vehicle objects in TestVehicle (e.g. sportscar, dumptruck, boat, suv, plane) • Use the default constructor from one test vehicle; prompt the user for other vehicles • Use get method to test retrieving data • Execute efficiency and range methods for each test vehicle • Efficiency = #passengers * mpg • Range = fuel capacity * mpg

  29. Exercise (2) • Write a test class named Rectangle • Instance data is width, height, and color • Override the default constructor • Provide a constructor which sets the instance data • Provide access methods for all data • Include a method to calculate area • Write a test class that prompts user for data, displays data, and shows area

  30. Java Workshop Content • Introduction • Variables, Arrays, and Strings • Operators, Conditions, and Loops • Object-Oriented Programming • Java Class Library • Class Methods and Data • Inheritance and Interfaces

  31. Java Packages Packages group related classes and interfaces: • To avoid naming conflicts • To distribute software • To protect classes Packages are hierarchical. Java expects a one-to-one mapping of package name and file system structure. Example: “java.lang.Math” indicates that Math is class in the lang package, and lang is a package within the java package. This also implies a directory named java, and subdirectory named lang.

  32. Common Java Packages

  33. The Math Class • Exponent Methods • double x = Math.pow(a, b) // ab • double x = Math.sqrt(a) // square root • double x = Math.exp(a) // ea • Sampling of other Methods • double x = Math.min(a, b) • double x = Math.max(a, b) • double x = Math.random() // 0 to <1 • Also refer to ElementK Workbook, p114 • Constants • PI // 3.14159… • E // 2.71828… = e1

  34. The String Class • Declare an object from the String class • Similar to declaring a variable from a primitive data type • Declare and create (construct) an object from a Class • Constructing a String: • String message = new String("Welcome Java!"); • String s = new String(); • String message = "Welcome Java!"; // shortcut • Common String Functions: • Length • Substrings • Compare to other Strings • Find and Replace • Convert Create object s with keyword new Declare object s from String class

  35. Common String Functions • Length returns #characters • str1.length(); • // because length is a method, you must use parentheses • Substring returns a String • str1.substring(iStartPos, iEndPos); • Compare to Other Strings • Cannot simply use the comparison operator == • str1.equals(str2); // returns T or F • str1.compareTo(str2); • // returns 0 if all chars equal, • // returns -n or n as difference between first unlike chars • str1.startsWith(str2); • Find and Replace • str1.indexOf(str2); // returns position • str1.replace(oldChar, newChar); str1 is an instance of a String length is an instance method

  36. Common String Functions cont. str1 is an instance of a String • Convert • str1.toLowerCase(); • str1.toUpperCase(); • str1.trim(); // removes blanks at string ends • String.valueOf(iNum); // convert numeric value to string toLowerCase is an instance method String is the class valueOf is a class-level (static) method

  37. The StringBuffer Class • StringBuffer objects are alterable • Constructing a StringBuffer object: • StringBuffer sB = new StringBuffer(“Bill");

  38. StringBuffer Functions • Append • sB.append(“added to the end.”); • Set Length of the Buffer • sB.setLength(value); • Return a String Representation • sB.toString() • // useful for functions that expect a String parameter. For example, System.out.println.

  39. Getting Input from Input Dialog Boxes String string = JOptionPane.showInputDialog( null, x, y, JOptionPane.QUESTION_MESSAGE); where x is a string for the prompting message and y is a string for the title of the input dialog box. E.g. x = “Enter a year”and y = “Example 2.2 Input”

  40. Converting Strings to Integers Input dialog box returns a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number. Convert a string into an int value: int intValue = Integer.parseInt(intStr); where intStr is a numeric string such as “123”.

  41. Sample Program:Get Data from Dialog Box

  42. Numeric Type Conversion (Casting) Casting is implicit and permitted when converting from a lower range to a higher range data type. Example: conversion is implicit from int to long, but an explicit conversion (cast) must be made from long to int. Why? Possible loss of data when converting to a lower range data type.

  43. Example of Implicit Conversion Consider the following statements: byte i = 100; long k = i*3+4; double d = i*3.1+k/2; int x = k; //(Wrong) long k = x; //(fine,implicit casting)

  44. Example of Explicit Conversion Cast explicitly by declaring, in parentheses, the type to which a variable is cast: double d = 4.5 int i = (int)d; // explicit casting Variable d, a variable of type double, is cast to (i.e. plays the role of) an int.

  45. Character Data • A character literal is enclosed in single quotes (e.g. ‘A’) • A string literal is enclosed in double quotes (e.g. “A”) • Java uses Unicode, a 16-bit scheme that incorporates ASCII (8-bit English characters) and most foreign language characters. • The following statements are equivalent: • char alpha = ‘A’; // ASCII • char alpha = ‘\u0041’; // Unicode • Sample of foreign language characters in Unicode: • String chineseCoffee = “\u5496\u5561”; • String greek = “\u03b1 \u03b2 \u03b3”;

  46. Conversion between Char and Int • Cast char to an int: Unicode value implicitly converted to int char greek = ‘\u03b1’; // Unicode int a = greek // Implicit cast to int • Cast an int to a char: only the lower 16 bits of the int are cast; and so a possible loss of data may occur. Thus explicit cast is required: • int b = 946; // Integer • char beta = (char)b // Explicit cast to char

  47. Compare Objects Equality operator (= =) used for primitive data. But for objects, equality operator returns true only if two variables refer to the same object. Must use the equals method to determine if two objects are meaningfully equivalent. Example: String name = “Bob”;String ref = new String(name);if (name == ref) // false System.out.println(“Reference same object”);if (name.equals(ref)) // true System.out.println(“Meaningfully equivalent”); Variables reference different objects, but are meaningfully equivalent. Both have string value “Bob”.

  48. Determine Class of an Object:instanceof To use appropriate methods, we need to know from which class an object was constructed. Sometimes, we may not immediately know an object’s class. For example, an Animal array may hold subclass objects Mammal, Bird, or Reptile. Use the instanceof operator to determine class of individual objects. Example: Animal[] zoo = new Animal[10];…if (zoo[j] instanceof Bird) zoo[j].fly() …

  49. Some Points to Remember (1) • Packages group related classes and interfaces • System, Math, String and other commonly used classes are implicitly imported into every Java program • The Math package provides static (class-level) methods to: • Calculate xy = x raised to the y power : Math.pow(x,y) • Calculate square root: Math.sqrt(x) • Determine min or max of two values Math.min(x,y) • Return a random number from 0 to <1 Math.random()

  50. Some Points to Remember (2) • String msg = new String (“Java Man”); // creates string object • String msg = “Java Man”; // shorthand notation creates string • Strings are concatenated with + operator • msg.length() returns # of characters in msg string • String data may contain alpha and numeric characters • Numeric 123 is not the same as Numeric String “123” • Convert String to Numeric with a parse method, depending on what numeric is expected • intValue = Integer .parseInt (intString); // intString is “123” • doubleVal = Double.parseDouble (dblString); // dblString = “123.45” • Convert Numeric to String with valueOf method: • String s = String.valueOf (123.45) • Get Input from User with Input Dialog Box • Input Dialog Box returns a String data type

More Related