380 likes | 514 Vues
Lecture objectives. Differences between Java and C# Understand and use abstract classes Casting in Java: why is it important? Master exceptions Create packages. Java vs C#. The More Things Change The More They Stay The Same. We Are All Objects Keyword Jumble
E N D
Lecture objectives • Differences between Java and C# • Understand and use abstract classes • Casting in Java: why is it important? • Master exceptions • Create packages CS340
Java vs C# CS340
The More Things Change The More They Stay The Same • 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 • Unextendable Classes • Throwing and Catching Exceptions • Member Initialization at Definition and Static Constructors CS340
The Same But Different • 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 • Array Declarations
Wish you were here… • Checked Exceptions • Cross Platform Portability (Write Once, Run Anywhere) • Extensions • Dynamic Class Loading • Interfaces That Contain Fields • Anonymous Inner Classes • Static ImportsArray Declarations CS340
Abstract classes CS340
Abstract Classes • 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 resultTypemethodName(parameterList); CS340
Example of an Abstract Class 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 • Can an interface have: • abstract methods? (no body) • concrete methods? (with a body) • data fields • Can an abstract class have: • abstract methods? (no body) • concrete methods? (with a body) • data fields • Can a concreteclass have: • abstract methods? (no body) • concrete methods? (with a body) • data fields CS340
Abstract Classes and Interfaces • 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 • 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 CS340
Class Object and Casting CS340
Class Object • 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 • You should always override toString method if you want to print object state • If you do not override it: • Object.toString will return a String • Just not the String you want! Example: ArrayBasedPD@ef08879 The name of the class, @, instance’s hash code CS340
Operations Determined by Type of Reference Variable • Java is strongly typedObject athing = new Integer(25); • What is the type of the variable athing? CS340
Operations Determined by Type of Reference Variable (cont.) • Why does the following generate a syntax error? Integer aNum = aThing; CS340
Casting in a Class Hierarchy • 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 • instanceof can guard against a ClassCastException Object obj = ...; if (objinstanceof Integer) { Integer i = (Integer) obj; intval = i; ...; } else { ... } CS340
Method Object.equals • 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() /** Determines whether the current object matches its argument. @paramobj 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; } }
A Java Inheritance Example—The Exception Class Hierarchy CS340
Run-time Errors or Exceptions • 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 • Throwable is the superclass of all exceptions • All exception classes inherit its methods CS340
Checked and Unchecked Exceptions • 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.) • 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 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. CS340
Checked and Unchecked Exceptions (cont.) • Class Error: due to serious external conditions • Example: OutOfMemoryError • Unchecked exception • The class Exception and its subclasses can be handled by a program • RuntimeException and its subclasses are unchecked CS340
Some Common Unchecked Exceptions • ArithmeticException: division by zero, etc. • ArrayIndexOutOfBoundsException • NumberFormatException: converting a “bad” string to a number • NullPointerException • NoSuchElementException: no more tokens available CS340
Handling Exceptions • Exception example on eclipse (java tutorial book) CS340
The try-catch Sequence • The try-catch sequence resembles an if-then-else 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 • Let’s try this example public static intgetIntValue(Scanner scan) { intnextInt = 0; // next int value booleanvalidInt = 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
Packages and Visibility CS340
Packages • 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 • Packages need to be imported • For example, x = Java.awt.Color.GREEN; • If the package is imported, the packageNameprefix is not required. import java.awt.Color; ... x = Color.GREEN; CS340
The Default Package • 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 your classes belong to the default package! CS340
Visibility Supports Encapsulation • 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.) • Encapsulation insulates against change • Greater visibility means less encapsulation • So… use the most restrictive visibility possible to get the job done! CS340