Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fall 2006CSC311: Data Structures1 Java Review. Fall 2006CSC311: Data Structures2 The Java Virtual Machine (JVM) Virtual machine -- the logical machine.

Similar presentations


Presentation on theme: "Fall 2006CSC311: Data Structures1 Java Review. Fall 2006CSC311: Data Structures2 The Java Virtual Machine (JVM) Virtual machine -- the logical machine."— Presentation transcript:

1 Fall 2006CSC311: Data Structures1 Java Review

2 Fall 2006CSC311: Data Structures2 The Java Virtual Machine (JVM) Virtual machine -- the logical machine (non- physical machine) that performs machine functions, typically implemented in software on top of a "real" hardware platform and operating system JVM -- the software implementation of a "CPU" designed to run compiled Java code Includes stand-alone Java applications, as well as "applets" that are downloaded and run in Web browsers such as the NetScape Navigator Thanks to the JVM, programs written in Java don't have to be rewritten to run on different computers Need an interpreter to translate JVM code to machine code

3 Fall 2006CSC311: Data Structures3 Class and Object What is a class? –A class is corresponding to a concept, e.g. People, Student, Faculty, Staff, Rectangle, Circle, etc –In Java, a class is a set of objects with the same behavior What is an object? –An object is corresponding an entity, e.g. Jack, Peter –In Java, an object is an entity that you can manipulate in your programs (by invoking methods) –Each object belongs to a class –Object constructions

4 Fall 2006CSC311: Data Structures4 Class Components Components –Fields – name, type and specifier –Methods – signature (prototype) –Constructors – object initialization Declaration –Variable declaration –Object variables w/o initialization –Method declaration // method calls

5 Fall 2006CSC311: Data Structures5 Data Types Data types –Primitive data types – int, long, short, double, float, boolean, char –Classes – String, Object Type conversion –Explicit type conversion – casting may cause information lost –Implicit type conversion – default no information lost

6 Fall 2006CSC311: Data Structures6 Casting and Autoboxing/Unboxing Casting: (type) expr Autoboxing –Implicit casting –Number – Integer, Double, Float, etc –Anytime a Number object is expected as a parameter to a method, the corresponding base type can be passed: Number  base type Unboxing –Anytime a base type is expected in an expression involving a Number reference, that Number object is changed to the corresponding base type base type  Number

7 Fall 2006CSC311: Data Structures7 Enum Types Declaration modifier enum name {vale_name 0, value_name 1, …, value_name n-1 Example Public enum Day{Mon, Tue, Wed, Thu, Fri, Sat, Sun}; Constants -- final

8 Fall 2006CSC311: Data Structures8 Statements Assignments – location Decisions –If-then –If-then-else –Switch-case Iterations –while –do-while –for Restricted gotos –break –continue –return Boolean expressions and short-circuit evaluation

9 Fall 2006CSC311: Data Structures9 Simple Input and Output Simple output methods: –Built-in static object: System.out An instance of java.io.PrintStream class –print(Object) –Print(String) –print(base_type) –Println(String) Simple input methods –Built-in special object: System.in –Related class: java.util.Scanner –Scanner sc = new Scanner(System.in); hasNext()next()hasNextType()nextType()hasNextLine()nextLine()findInLine(String)

10 Fall 2006CSC311: Data Structures10 Designing classes Choosing classes –A class represents a single concept Concepts from mathematics: Point, Rectangle, Ellipse Concepts from real life: BankAccount, Person, Student –Utility classes--no objects, only static methods Math Principles: –Responsibilities –Independence –Behaviors

11 Fall 2006CSC311: Data Structures11 Designing classes Cohesion and Coupling –Cohesive: all methods are closely related to the single concept that the class represents –Coupling: A class depends on another if it calls one of its methods High Coupling  many class dependencies Minimize coupling to minimize the impact of interface changes

12 Fall 2006CSC311: Data Structures12 Accessor and Mutator Classes Accessor: does not change the state of the implicit parameter (e.g. getBalance()) Mutator: changes the state of the implicit parameter (e.g. deposit(double amount ) Rule of thumb: Mutator should return void Immutable class: all methods are accessors (e.g. String)

13 Fall 2006CSC311: Data Structures13 Preconditions/postconditions Precondition –The condition that must be met before the method executes –Publish preconditions so the caller won't call methods with bad parameters Postcondition –The condition that's true after a method has completed –If not, the method functioned incorrectly

14 Fall 2006CSC311: Data Structures14 Scope Scope of variable: region of program where the variable can be referred by its name –Local variable scope: from definition to end of block –Class scope: all methods of the class –Overlapping scope: local scope wins over class scope Static scope –Static fields Define a field that belongs to a class instead of any object Non-static fields are instance fields, while static fields are class fields Minimize the use of static fields –Static methods No implicit parameter Too many static methods are a sign of too little Object-oriented

15 Fall 2006CSC311: Data Structures15 Coding and Pseudo-code Coding –programming in Java –IDE Pseudo-code –Mixes natural language with standard programming language constructs –Constructs: Expressions Method declarations Decision structures Loop structures Array indexing Method calls Method returns comments

16 Fall 2006CSC311: Data Structures16 Object-oriented Design Goals –Robustness –Adaptability –Reusability Principles –Abstraction –Encapsulation –Modularity Design Patterns –Describe a solution to a typical software design problem –Some typical design patterns: Position, Adaptor, Iterator, Template method, Composition, Comparator, Amortization, Divide-and-conquer, etc.

17 Fall 2006CSC311: Data Structures17 Inheritance Specialization and generalization (extension) –Specialization – subclass –Generalization -- superclass Method overriding –Refinement –Replacement The keyword this

18 Fall 2006CSC311: Data Structures18 Inheritance Hierarchies Hierarchies of classes, subclasses, and sub- subclasses are common Similar to concept hierarchies: –Person has subclasses like Faculty, Student, Staff; –Faculty may have subclasses FullTimeFaculty and PartTimeFaculty; –FullTimeFaculty may have TenuredFaculty and TenureTrackFaculty; –Student may have subclasses FullTimeStudent and PartTimeStudent; –etc. A superclass can have multiple subclasses, but a subclass should have at most ONE superclass

19 Fall 2006CSC311: Data Structures19 Inheritance of Methods Override method: Supply a different implementation of a method that exists in the superclass Inherit method: Don't supply a new implementation of a method that exists in the superclass Add method: Supply a new method that doesn't exist in the superclass Subclass can not access the private methods of superclass Calling a Superclass Method/constructor

20 Fall 2006CSC311: Data Structures20 Inheritance of Fields Inherit field: All fields from the superclass are automatically inherited Add field: Supply a new field that doesn't exist in the superclass Can't override fields Subclass can not access the private fields of superclass

21 Fall 2006CSC311: Data Structures21 Polymorphism Polymorphism (greek: many shapes): The type of the object determines the method to call Called late binding. Resolved at runtime Different from overloading. Overloading is resolved by the compiler Converting from subclasses to superclass The instanceof method –Test whether an object is of a specified class –Example: x instanceof String to test if x is a string

22 Fall 2006CSC311: Data Structures22 Access control public – accessible anywhere private – accessible inside the class protected -- accessible by class, subclasses and package default – no specifier, accessible by package Recommended Access Levels –Fields: Always private Exception: public static final constants –Methods: public or private –Classes: public or package –Don't use protected –Beware of accidental package access (forgetting public or private)

23 Fall 2006CSC311: Data Structures23 The Object Object The Cosmic Superclass All classes extend Object by default Most useful methods: – –String toString(): to convert the object to a string message – –boolean equals(Object otherObject): to test if the object is equal to the given object otherObject – –Object clone(): to create a new copy of the object

24 Fall 2006CSC311: Data Structures24 Exceptions Throwing exceptions Catching exceptions –Try-catch-finally block try { … } catch (exception_type1 e1) { … } catch (exception_type2 e2) { … } … finally { … } finally { … }

25 Fall 2006CSC311: Data Structures25 Interfaces Special classes All methods in an interface are abstract –no implementation All methods in an interface are automatically public An interface doesn't have instance fields An interface doesn’t have constructors Interface implementation –Should be implemented by classes Multiple inheritance in Interfaces

26 Fall 2006CSC311: Data Structures26 Abstract Class and Method Abstract class –Cannot have direct instances (objects) –Must be extended by subclass(es) –Can implement some methods (main difference from interfaces) Abstract method –Must be overridden by subclass(es) –Must be inside abstract classes –Non-abstract class cannot have abstract method

27 Fall 2006CSC311: Data Structures27 Strong Typing Strong typing –All variables must be typed Java –A strong-typing language –An object can be viewed as being of various types –But declared as being of only one type

28 Fall 2006CSC311: Data Structures28 Generics Casting –Widening conversion: to superclass –Narrowing conversion: to subclass –Casting exception –Casting with interfaces Generics –Generic type: a type that is not defined at compilation time, but becomes fully specified at run time –Formal type parameters –Actual type parameters

29 Fall 2006CSC311: Data Structures29 Generics: Example public class Pair { K key; V value; public void set(K k, V v) { key = k; value = v; } public K getKey() { return key; } public V getValue() { return value; } } Public static void main(String[] args) { Pair pair1 = new Pair (); pair1.set(new String(“height”), new Integer(36)); Pair pair2 = new Pair (); pair2.set(new Student(“A5678”, “Sue”, 19), new Double(9.5)); }}

30 Fall 2006CSC311: Data Structures30 Arrays A set of data cells with fixed size, each cell holding a data item and all data items being the same type Purpose: to construct a linear structure to hold a given number of elements. Once an array is created, its size is fixed – length Indices starting from 0 Common algorithms on arrays –Find max/min values –Find average value –Linear search Copying array and clone array High-dimensional arrays

31 Fall 2006CSC311: Data Structures31 Array List ArrayList is a class – data type Purpose: to construct a linear structure to hold a flexible number of elements Methods: –size() – returns the number of elements in the ArrayList: a.size() –get( ) – returns the -th element that is the type of Object should convert the return value to your specific type The starts at 0 –set(, ) – sets the -th element to, overwrites the old element –add(, ) – adds before the -th element –remove( -th element

32 Fall 2006CSC311: Data Structures32 Recursion A recursive computation solves a problem by using the solution of the same problem with simpler input For recursion to terminate, there must be special cases for the simplest inputs The simplest case can be directly solved The recursive cases should call the method itself


Download ppt "Fall 2006CSC311: Data Structures1 Java Review. Fall 2006CSC311: Data Structures2 The Java Virtual Machine (JVM) Virtual machine -- the logical machine."

Similar presentations


Ads by Google