Download presentation
Presentation is loading. Please wait.
Published byDeirdre Long Modified over 9 years ago
1
Lecture objectives Differences between Java and C# Understand and use abstract classes Casting in Java: why is it important? Master exceptions Create packages CS340 1
2
Java vs C# 2 CS340
3
The More Things Change The More They Stay The Same We Are All Objects We Are All Objects Keyword Jumble Keyword Jumble Of Virtual Machines and Language Runtimes Of Virtual Machines and Language Runtimes Heap Based Classes and Garbage Collection Heap Based Classes and Garbage Collection Arrays Can Be JaggedArrays Can Be Jagged No Global Methods No Global Methods Interfaces, Yes. Multiple Inheritance, No. Interfaces, Yes. Multiple Inheritance, No. Strings Are Immutable Strings Are Immutable CS340 3
4
The More Things Change The More They Stay The Same Unextendable Classes Unextendable Classes Throwing and Catching Exceptions Throwing and Catching Exceptions Member Initialization at Definition and Static Constructors Member Initialization at Definition and Static Constructors CS340 4
5
The Same But Different Main Method Main Method Inheritance Syntax Inheritance Syntax Run Time Type Identification (is operator) Run Time Type Identification (is operator) Namespaces Namespaces Constructors, Destructors and Finalizers Constructors, Destructors and Finalizers Synchronizing Methods and Code Blocks Synchronizing Methods and Code Blocks Access Modifiers Access Modifiers Reflection Reflection Declaring Constants Declaring Constants Primitive Types Primitive Types Array Declarations Array Declarations 5
6
Wish you were here… Checked Exceptions Checked Exceptions Cross Platform Portability (Write Once, Run Anywhere) Cross Platform Portability (Write Once, Run Anywhere) Extensions Extensions Dynamic Class Loading Dynamic Class Loading Interfaces That Contain Fields Interfaces That Contain Fields Anonymous Inner Classes Anonymous Inner Classes Static Imports Array Declarations Static ImportsArray Declarations 6 CS340
7
Abstract classes CS340 7
8
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 resultType methodName (parameterList); CS340 8
9
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 9
10
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 concrete class have: – abstract methods? (no body) – concrete methods? (with a body) – data fields CS340 10
11
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 11
12
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 12
13
Summary of Features of Actual Classes, Abstract Classes, and Interfaces CS340 13
14
Class Object and Casting 14 CS340
15
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 15
16
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 16
17
Operations Determined by Type of Reference Variable Java is strongly typed Object athing = new Integer(25); What is the type of the variable athing ? CS340 17
18
Operations Determined by Type of Reference Variable (cont.) Why does the following generate a syntax error? Integer aNum = aThing; CS340 18
19
Casting in a Class Hierarchy Casting does not change the object! It creates an anonymous reference to the object Integer aNum = (Integer) aThing; CS340 19
20
Using instanceof to Guard a Casting Operation instanceof can guard against a ClassCastException Object obj =...; if (obj instanceof Integer) { Integer i = (Integer) obj; int val = i;...; } else {... } CS340 20
21
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 21
22
Employee.equals() /** 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; } 22
23
A Java Inheritance Example—The Exception Class Hierarchy 23 CS340
24
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 24
25
Class Throwable Throwable is the superclass of all exceptions All exception classes inherit its methods CS340 25
26
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 26
27
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 CS340 27 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.
28
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 28
29
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 29
30
Handling Exceptions Exception example on eclipse (java tutorial book) CS340 30
31
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... } 31
32
Using try-catch 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 32
33
Packages and Visibility 33 CS340
34
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 34
35
Packages and Visibility 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 35
36
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 36
37
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 37
38
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 38
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.