Download presentation
Presentation is loading. Please wait.
Published byCassandra Marsh Modified over 9 years ago
1
Appendix A.1: Review of Java and Object-Oriented Programming: Part 1 “There does not now, nor will there ever, exist a programming language in which it is the least bit hard to write bad programs.” – L. Flon
2
©SoftMoore ConsultingSlide 2 Model for Programming Software Objects Programmer’s Representation of the Problem Results Execution/ Interpretation of the Results Real World Objects Problem Space Solution Space Addition of new Solution Space Objects
3
©SoftMoore ConsultingSlide 3 File Structure Each public Java class requires its own source file. Source file –base name equals class name –extension is “.java ” Object (class) file –contains java bytecode (architecture neutral) –base name equals class name –extension is “.class ” –directory structure parallels package structure
4
©SoftMoore ConsultingSlide 4 The Class Path CLASSPATH –environment variable specifying where the JVM should look for user-defined classes –list of directories, JAR files, and ZIP files –location of system classes is appended to the end of the list Class path list entry separators –“:” (colon) for Unix –“;” (semicolon) for Windows Example.;C:\java\classes;C:\xerces-1_4_4\xerces.jar
5
©SoftMoore ConsultingSlide 5 Primitive Data Types Integer Types –int– short –long– byte Floating Point Types –float– double Type char Type boolean
6
©SoftMoore ConsultingSlide 6 The char Type Uses Unicode UTF-16 encoding –16 bit code units (usually code unit = character) –supplementary characters encoded in two code units –can be expressed as hexadecimal values \u0000 to \uffff Alternate escape sequences for special characters –'\n' newline \u000a –'\t' horizontal tab \u0009 –'\r' carriage return \u000d –'\b' backspace \u0008 –'\'' apostrophe (single quote) \u0027 –'\"' double quote \u0022 –'\\' backslash \u005c
7
©SoftMoore ConsultingSlide 7 Overloaded Method Names Method names can be overloaded provided that each signature (number and types of arguments) is unique. String substring(int beginIndex) String substring(int beginIndex, int endIndex) From a user point of view, each method provides the same kind of service even though each is implemented in a different way. It makes a program easier to understand. The method's return type is not used in resolving references to overloaded methods.
8
©SoftMoore ConsultingSlide 8 Object Variables and Reference Types Example public class PurchaseOrder { … } PurchaseOrder order = new PurchaseOrder(); The variable order is a reference to the object created by new – order is not the object itself. the PurchaseOrder object the object reference to the object order
9
©SoftMoore ConsultingSlide 9 Method Arguments All arguments to Java methods are passed by value (copy in). Changing the formal argument does not change the actual argument. Java passes only references to objects as method arguments, not the objects themselves. Those references are passed by value.
10
©SoftMoore ConsultingSlide 10 Method Example: Greatest Common Divisor public static int gcd(int a, int b) { int a1, b1, temp; a1 = (a > 0) ? a : -a; // a1 = abs(a); b1 = (b > 0) ? b : -b; // b1 = abs(b) while (b1 != 0) { temp = a1; a1 = b1; b1 = temp % b1; } return a1; }
11
©SoftMoore ConsultingSlide 11 Variable Parameters (a.k.a. “Varargs”) Motivation: To allow methods to have a variable number of parameters Example – printf() method introduced in Java 5 System.out.printf("%s %3d", name, age); Prior to Java 5 you had to use an array to simulate this functionality.
12
©SoftMoore ConsultingSlide 12 Using Variable Parameters Syntax public PrintStream printf(String format, Object... args) Ellipsis (... ) is part of the syntax Parameter args has type Object[]
13
©SoftMoore ConsultingSlide 13 The March of Progress (Cay Horstmann) 1980: C printf("%10.2f", x); 1988: C++ cout << setw(10) << setprecision(2) << showpoint << x; 1996: Java java.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance(); formatter.setMinimumFractionDigits(2); formatter.setMaximumFractionDigits(2); String s = formatter.format(x); for (int i = s.length(); i < 10; i++) System.out.print(' '); System.out.print(s); 2004: Java System.out.printf("%10.2f", x);
14
©SoftMoore ConsultingSlide 14 Access Control public –part of the public interface of the class –visible to any client of the class protected –not part of the public interface of the class –visible to any subclass and any class within same package –essentially public to subclasses and classes in the same package, and private to the rest of the program package (no explicit modifier) –visible only to classes within same package private –visible only to enclosing class
15
©SoftMoore ConsultingSlide 15 Package Collection of classes Namespace control; e.g., public class Test extends java.awt.Frame {... } or import java.awt.Frame; … public class Test extends Frame { … } Supports data hiding –public classes are visible to code outside of package –classes with no access modifier are not visible outside the package
16
©SoftMoore ConsultingSlide 16 Example: Packages Customer.java: package com.softmoore.sales; public class Customer {...} // public access class Credit {...} // package access Display.java: package com.softmoore.ui; import com.softmoore.sales.*; public class Display { Customer c = new Customer(); // o.k. Credit cr = new Credit(); // *** ERROR *** }
17
©SoftMoore ConsultingSlide 17 Dynamic Loading Java has no explicit link phase Imagine a program made up of nothing but DLLs Class definitions are loaded on demand CLASSPATH is searched for file T.class
18
Immutable Class A class is said to be immutable if its instances cannot be modified after construction. Guidelines for making a class immutable –Don’t provide methods that modify the object’s state. –Ensure that the class can’t be extended (e.g., make it final). –Make all fields private and final. Examples in Java –String– Wrapper classes– BigInteger Immutable objects are simple and inherently thread-safe. ©SoftMoore ConsultingSlide 18 “Classes should be immutable unless there is a very good reason to make them mutable” – Joshua Bloch
19
Wrapper Classes Each Java primitive type has an equivalent class type called a “wrapper” class. –Integer– Byte –Float– Double –Character– … The wrapper classes contain –public constants that provide attributes of the primitive type, such as MAX_VALUE and SIZE. –methods for converting to other types, such as String or int All wrapper class names begin with a capital letter. The wrapper classes are immutable.
20
©SoftMoore ConsultingSlide 20 Strings Functionality is provided by standard class java.lang.String (not a primitive type). Java strings are immutable – constant length and content. Use class java.lang.StringBuffer or class java.lang.StringBuilder for mutable strings. Examples String s0 = new String("Hello"); String s1 = "Hello"; // short-hand notation String s2 = "world"; String s3 = s1 + ", " + s2; // "Hello, world" String s4 = "j" + s1.substring(1, 5); // "jello" Prefer method equals() when comparing strings.
21
©SoftMoore ConsultingSlide 21 The StringBuffer Class Defined in java.lang.StringBuffer Provides methods for splicing together characters and substrings Provides various insert/append methods Class StringBuffer is designed to be thread-safe, and all public methods in StringBuffer are synchronized. Example StringBuffer b = new StringBuffer("HelloWorld"); b.insert(5, ", "); b.append(".");
22
©SoftMoore ConsultingSlide 22 The StringBuilder Class Defined in java.lang.StringBuilder Provides an API compatible with StringBuffer, but with no guarantee of synchronization. Can be used as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Recommendation: Use StringBuilder in preference to StringBuffer since it will be faster under most implementations.
23
©SoftMoore ConsultingSlide 23 Default Constructor A default constructor is one that has no arguments Example public class X { public X() { … } … } … X x1 = new X();
24
©SoftMoore ConsultingSlide 24 Copy Constructor A copy constructor is used to initialize a newly created object with an existing object of the same class. A copy constructor has a single argument that is a reference to an object of the same class as the constructor. Example public class X { public X() { … } // default constructor public X(X x) { … } // copy constructor … }; X x1 = new X(); // calls default constructor X x2 = new X(x1); // calls copy constructor
25
©SoftMoore ConsultingSlide 25 Conversion Constructor A constructor that creates an object of one class and initializes it with the value of an object of a different class is sometimes referred to as a conversion constructor (converts from one class to another). A conversion constructor has exactly one argument Example public class Fraction { public Fraction(int n) { … } … } Fraction f1 = new Fraction(5); // converts integer 5 to Fraction 5/1
26
©SoftMoore ConsultingSlide 26 General Constructor A general constructor is one that does not fit any of the other special categories. (none of the above) Example public class Date { public Date(int year, int month, int day) { … } … } Date today = new Date(1993, 1, 3); The constructor for class Date is not a default constructor, a copy constructor, or a conversion constructor.
27
©SoftMoore ConsultingSlide 27 Information Hiding with Java Fields are usually declared to be private. Access to private fields is usually restricted to an explicitly declared list of public methods. Debugging benefit – all access to data is localized; any illegal value must be caused by a method. Maintenance benefit – prevents dependencies on the underlying representation details; changes do not affect user programs. Information hiding is enforced by the language.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.