440 likes | 563 Views
Object Oriented Programming (4) Prof. Lixin Gao. Today’s Topics. Constructor Static and Final Organize multiple files/classes Nesting Class Java Package / Import Package String Class Exception/Throw. Default Constructor in Class. No constructor in a class
E N D
Object Oriented Programming (4) Prof. Lixin Gao
Today’s Topics • Constructor • Static and Final • Organize multiple files/classes • Nesting Class • Java Package / Import Package • String Class • Exception/Throw
Default Constructor in Class • No constructor in a class • By default, Java creates a non-parameter constructor for the class • At least one constructor in a class • Java will not create a non-parameter constructor for the class
Example: Default Constructor EmployeeDefaultConstructor.java public class EmployeeDefaultConstructor { private String name; private String tel; public static void main(String[] args) { EmployeeDefaultConstructor gao=new EmployeeDefaultConstructor (); } } Call default constructor: Employee( )
Constructors in Subclass • There is an explicit constructor • Can call constructor in superclass • super(n,t) must be in the first line • If there is no call of constructor in superclass, Java implicitly calls of non-parameter constructor in superclass • No explicit constructor • Java creates non-parameter constructor that calls non-parameter constructor in superclass
Example of Incorrect Constructor EmployeeConstructorError1.java, FacultyConstructorError1.java public class EmployeeConstructorError1 { protected String name, tel; EmployeeConstructorError1(String n, String t) { name = n; tel = t; } } public class FacultyConstructorError1 extends EmployeeConstructorError1 { private String secName; public FacultyConstructorError1(String n, String t, String s) { name =n; tel = t; secName = s; } } Error: Should call super(n, t) explicitly here, Or, have a non-parameter constructor in superclass Give an compilation error
Lack of A Constructor EmployeeConstructorError2.java, FacultyConstructorError2.java public class EmployeeConstructorError2 { private String name, tel; EmployeeConstructorError2(String n, String t) { name = n; tel = t; } } public class FacultyConstructorError2 extends EmployeeConstructorError2 { private String secName; public static void main(String[] args) { FacultyConstructorError2 lixin = new FacultyConstructorError2( ); } } Cannot find a non-parameter constructor in superclass, give a compilation error
Static, Final, and Public/Private • Static variable vs. Instance variable • Static method vs. method • Final variable • Final method • Public/Private variable/method
Static Variable/Method • Static variable/method • No need for an object associated with the operations • Main method has to be static • Static variable/method can be public or private • Variable/method is not static by default
Static Variable Examples: CircleArea.java class CircleArea { static double pai = 3.1415926; double radius; CircleArea( double r ) { radius = r; } public static void main(String args[]) { CircleArea cir = new CircleArea(2.0); double area = pai * cir.radius * cir.radius; System.out.println("Area of this circle is " + area); } }
Static Method class CallCubeFunction { static public double cube(double n) { return (n*n*n); } public static void main(String args[]) { double length = 3.0; double itsCube; itsCube = cube(length); System.out.println("Its cube is " + itsCube); } }
Access Control • Public/protected/private • public: access from any class • protected: access from this class and subclass • private: access only from this class • Final • final variables: can not be modified, similar to constant in C/C++ language • final methods: can not be overridden by subclass.
Final Variables • Can not modify the value for final variables public class CityName { final static private String name = "Amherst"; public static void main(String args[]) { System.out.println("City name is " + name ); } } • In CityName.java, you can not change name in any method because name is final
Final Method • Complete Example: • VerifyPinWithFinal.java • CallingVerifyPinWithFinal.java • VerifyPinWithoutFinal.java • CallingVerifyPinWithoutFinal.java • There is a VerifyPin() method in super class • Don’t allow Subclass to override VerifyPin() • Otherwise, someone can be cheating
With Final vs. Without Final • Use final to declare VerifyPin() method • compiling error if overriding VerifyPin() method • Can not cheat during verification • Don’t use final to declare VerifyPin() method • always return TRUE in Overriding VerifyPin() • Easy to cheat during verification, not secure for the program
Organize multiple files/classes • Each class in one file, for examples: • Employee class will be in Employee.java • Faculty class will be in Faculty.java • Staff class will be in Staff.java
Nesting Class • One class is nested in the other class • Both classes are in the same file • Advantage: • Instance variables and methods are private in inner-class, but they can be accessible directly from outer-class
Employee Nested In Faculty Complete Example: FacultyNesting.java public class FacultyNesting { private class Employee { private name; private tel; … … } Employee emp; }
Employee Nested In Faculty In FacultyNesting.java public void printinfo( ) { System.out.println(emp.name + " 's tel is " + emp.tel); } public static void main(String[] args) { FacultyNesting lixin = new FacultyNesting("Lixin", "5678", "June"); lixin.printinfo(); lixin.emp.tel = "4548"; lixin.printinfo(); } All private instance variables and methods in Employee class can be accessible in FacultyNesting class.
Package • Package: the single unit in which Java provides a powerful means of grouping related classes together • Declaring Packages • package Identifier • Importing Packages • import Identifier
Print Out Today’s Date Complete Example: GetTimeWithImport.java import java.util.*; // import java.util packages class GetTimeWithImport { public static void main(String args[]) { Date today = new Date(); System.out.println("Today is " + today.toString() ); } }
Without Import Statement Complete Example: GetTimeWithoutImport.java // This file can not be compiled successfully !!! class GetTimeWithoutImport { public static void main(String args[]) { Date today = new Date(); System.out.println("Today is " + today.toString() ); } }
Import Statement • Make predefined package or class visible • import java.io.*; java.io package • import java.util.*; java.util package • Many common packages have been imported by default, such as java.lang.*
JDK Document • Useful link for JDK Document • http://java.sun.com/j2se/1.3/docs/api/index.html • Useful link for search JDK classes/API • http://java.sun.com/j2se/1.3/search.html
String class • Compare two Strings • Convert String to int • Convert int to String
Compare two Strings • Let’s see the example first, TestCompareString.java class TestCompareString { public static void main(String args[]) { String string1 = new String("Identical"); String string2 = new String("Identical"); if (string1 == string2) System.out.println("these two strings are identical"); else System.out.println("these two strings are not identical"); } }
Why? • Now you will get surprising result: these two strings are not identical • What’s wrong?
Compare two Strings • Another example, EqualCompareString.java class EqualCompareString { public static void main(String args[]) { String string1 = new String("Identical"); String string2 = new String("Identical"); if ( string1.equals(string2) ) System.out.println("these two strings are identical"); else System.out.println("these two strings are not identical"); } }
Result • Now you will get result: these two strings are identical • Results are different for these two conditions • if ( string1 == string2 ) • if ( string1.equals(string2) )
Compare Strings • How to compare two Strings • Syntax: string1.compareTo(string2) • 0: two strings are equal • >0: string 1 is greater than string 2 • <0: string 1 is less than string 2 • Example: CompareTwoString.java
String to Int • Convert String to int • Integer.parseInt(strAge); • Example String strAge = “21”; int iAge; iAge = Integer.parseInt(strAge);
Int to String • Convert int to String • Integer.toString(int); • Example int iScore = 89; String sScore; sScore = Integer.toString(iScore).
Purpose Of Exception • Once unexpected error occurs in our code, what can we do? • Exceptions • Changing the flow of control when some important or unexpected event has occurred • Try to cope with the error, or at least die gracefully
Exception Handling • try-catch blocks allow Java program to handle error conditions • try to execute the code in try block • if unexpected error occurs, execute the code in catch block • throw statement raises an exception
Triggering An Exception • Complete Example: DivisionError.java public class Division { public static void main( String[] args) { int i=1, j=0, k; k = i/j; // cause division-by-zero error } } Result: Exception in thread "main" java.lang.ArithmeticException: / by zero at Division.main(Division.java:4)
Catch An Exception Complete Example: DivisionErrorCatch.java public class DivisionErrorCatch { public static void main( String[] args) { int i=1, j=0, k; try { k = i/j; // cause division-by-zero error } catch (Exception e) { System.out.println("Catch an exception at main function"); } } }
Result For Exception Catch an exception at main function Press any key to continue . . . So this Exception e is an ArithmeticException
Try-Catch Matching • Nearest catch block prepared to handle the exception gets control • Following catch block, execution continues at the next statement following the entire try-catch block
Exception statement try { // some statements that may produce exceptions } catch (Exception e) { // handle exception object e } catch (AnotherException e) { // handle exception object e }
Exception Handling Example • Complete Example: ExceptionHandling.java int array[ ] = new int [10]; for( int i=0; i<15; i++ ) { try { array[i] =100 /(i-5); } catch( ArithmeticException e ) { System.err.println(" Divided by zero when index = " + i); } catch (Exception e) { System.err.println(" Error subscript in array, index=" + i); } }
Throw Example • Input a positive number n • Create an array with capacity n • If n is non-positive, throw an IllegalArgumentException • Complete Example:ThrowStatement.java
Throw Statement public class ThrowStatement { public static void main(String args[]) { EasyIn easy = new EasyIn(); System.out.print("Please input number: "); int n = easy.readInt(); int array []; if( n >0 ) array = new int [n]; else throw new IllegalArgumentException (" n must be >0 "); System.out.println("Array has been created here"); } }
Illegal Exception Types • There are many Illegal Exception types: • IllegalAccessError • IllegalAccessException • IllegalArgumentException • IllegalPathStateException • IllegalStateException • … … • More information: http://java.sun.com/j2se/1.3/docs/api/index.html
Summary For Exception • try-catch makes programming robust and also can make it still running even if some unexpected errors occur • throw will give a decent error message out explaining what failed and where and why