Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Lecture objectives 1 Differences between Java and C# Understand and use abstract classes Casting in Java: why is it important? Master exceptions Create packages CS340 2 Java vs C# CS340 The More Things Change The More They Stay The Same 3 We Are All Objects Keyword Jumble Of Virtual Machines and Language Runtimes Heap Based Classes and Garbage Collection Arrays Can Be Jagged No Global Methods Interfaces, Yes. Multiple Inheritance, No. Strings Are Immutable CS340 The More Things Change The More They Stay The Same 4 Unextendable Classes Throwing and Catching Exceptions Member Initialization at Definition and Static Constructors CS340 The Same But Different 5 Main Method Inheritance Syntax Run Time Type Identification (is operator) Namespaces Constructors, Destructors and Finalizers Synchronizing Methods and Code Blocks Access Modifiers Reflection Declaring Constants Primitive Types Wish you were here… 6 Checked Exceptions Cross Platform Portability (Write Once, Run Anywhere) Extensions Dynamic Class Loading Interfaces That Contain Fields Anonymous Inner Classes Static Imports Array Declarations CS340 7 Abstract classes CS340 Abstract Classes 8 Syntax: visibility abstract class className Difference from other classes: • An abstract class cannot be instantiated • An abstract class may declare abstract methods Includes abstract methods: visibility abstract resultType methodName (parameterList); CS340 Example of an Abstract Class 9 public abstract class Food { public final String name; private double calories; // Actual methods public double getCalories () { return calories; } protected Food (String name, double calories) { this.name = name; this.calories = calories; } // Abstract methods public abstract double percentProtein(); public abstract double percentFat(); public abstract double percentCarbs(); } CS340 Interfaces, Abstract Classes, and Concrete Classes 10 – Can an interface have: – – – • Can an abstract class have: – – – • abstract methods? (no body) concrete methods? (with a body) data fields abstract methods? (no body) concrete methods? (with a body) data fields Can a concrete class have: – – – abstract methods? (no body) concrete methods? (with a body) data fields CS340 Abstract Classes and Interfaces 11 • • • • • • Can an interface – be instantiated? – declare abstract methods? Can an abstract class – be instantiated? – declare abstract methods? Can an interface have constructors? Can an abstract class have constructors? Can an abstract class implement an interface? Can an interface implement an abstract class? CS340 Inheriting from Interfaces vs Classes 12 A class can extend 0 or 1 superclass An interface cannot extend a class A class or interface can implement 0 or more interfaces CS340 Summary of Features of Actual Classes, Abstract Classes, and Interfaces 13 CS340 14 Class Object and Casting CS340 Class Object 15 Object is the root of the class hierarchy Every class has Object as a superclass All classes inherit the methods of Object but may override them CS340 Method toString 16 You should always override toString method if you want to print object state If you do not override it: will return a String Just not the String you want! Example: ArrayBasedPD@ef08879 The name of the class, @, instance’s hash code Object.toString CS340 Operations Determined by Type of Reference Variable 17 Java is strongly typed Object athing = new Integer(25); What CS340 is the type of the variable athing? Operations Determined by Type of Reference Variable (cont.) 18 Why does the following generate a syntax error? Integer aNum = aThing; CS340 Casting in a Class Hierarchy 19 Casting does not change the object! It creates an anonymous reference to the object Integer aNum = (Integer) aThing; CS340 Using instanceof to Guard a Casting Operation 20 • instanceof can guard against a ClassCastException Object obj = ...; if (obj instanceof Integer) { Integer i = (Integer) obj; int val = i; ...; } else { ... } CS340 Method Object.equals 21 Object.equals method has a parameter of type Object public boolean equals (Object other) { ... } Compares two objects to determine if they are equal A class must override equals in order to support comparison CS340 Employee.equals() 22 /** Determines whether the current object matches its argument. @param obj The object to be compared to the current object @return true if the objects have the same name and address; otherwise, return false */ @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (this.getClass() == obj.getClass()) { Employee other = (Employee) obj; return name.equals(other.name) && address.equals(other.address); } else { return false; } } 23 A Java Inheritance Example—The Exception Class Hierarchy CS340 Run-time Errors or Exceptions 24 Run-time errors occur during program execution (i.e. at run-time) occur when the JVM detects an operation that it knows to be incorrect cause the JVM to throw an exception Examples of run-time errors include division by zero array index out of bounds number format error null pointer exception CS340 Class Throwable 25 Throwable is the superclass of all exceptions All exception classes inherit its methods CS340 Checked and Unchecked Exceptions 26 Checked exceptions normally not due to programmer error Must be explicitly caught all input/output errors are checked exceptions Extend class java.lang.Exception Examples: IOException, FileNotFoundException CS340 Checked and Unchecked Exceptions (cont.) 27 Unchecked exceptions result from programmer error (try to prevent them with defensive programming). They do not have to be caught a serious external condition that is unrecoverable Extend class java.lang.RuntimeException Examples: NullPointerException, ArrayIndexOutOfBoundsException CS340 Checked and unchecked exceptions are functionally equivalent. There is nothing you can do with checked exceptions that cannot also be done with unchecked exceptions, and vice versa. Checked and Unchecked Exceptions (cont.) 28 Class Error: due to serious external conditions Example: OutOfMemoryError Unchecked exception The class Exception and its subclasses can be handled by a program CS340 RuntimeException and its subclasses are unchecked Some Common Unchecked Exceptions 29 ArithmeticException: division by zero, etc. ArrayIndexOutOfBoundsException NumberFormatException: converting a “bad” string to a number NullPointerException NoSuchElementException: no more tokens available CS340 Handling Exceptions 30 Exception example on eclipse (java tutorial book) CS340 The try-catch Sequence 31 The try-catch sequence resembles an if-thenelse statement try { // Execute the following statements until an // exception is thrown ... // Skip the catch blocks if no exceptions were thrown } catch (ExceptionTypeA ex) { // Execute this catch block if an exception of type // ExceptionTypeA was thrown in the try block ... } catch (ExceptionTypeB ex) { // Execute this catch block if an exception of type // ExceptionTypeB was thrown in the try block ... } Using try-catch 32 Let’s try this example public static int getIntValue(Scanner scan) { int nextInt = 0; // next int value boolean validInt = false; // flag for valid input while(!validInt) { try { System.out.println("Enter number of kids: "); nextInt = scan.nextInt(); validInt = true; } catch (InputMismatchException ex) { scan.nextLine(); // clear buffer System.out.println("Bad data-enter an integer"); } } return nextInt; } CS340 33 Packages and Visibility CS340 Packages 34 A Java package is a group of cooperating classes The Java API is organized as packages Syntax: package classPackage; Classes in the same package should be in the same directory (folder) The folder must have the same name as the package Classes in the same folder must be in the same package CS340 Packages and Visibility 35 Packages need to be imported For example, x = Java.awt.Color.GREEN; If the package is imported, the packageName prefix is not required. import java.awt.Color; ... x = Color.GREEN; CS340 The Default Package 36 Files which do not specify a package are part of the default package If you do not declare packages, all of your classes belong to the default package Bad programming practice: All CS340 your classes belong to the default package! Visibility Supports Encapsulation 37 Visibility rules enforce encapsulation in Java private: for members that should be invisible even in subclasses package: shields classes and members from classes outside the package protected: provides visibility to extenders of classes in the package public: provides visibility to all CS340 Visibility Supports Encapsulation (cont.) 38 Encapsulation insulates against change Greater visibility means less encapsulation So… use the most restrictive visibility possible to get the job done! CS340