1 / 44

Object Oriented Programming (4) Prof. Lixin Gao

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

rian
Download Presentation

Object Oriented Programming (4) Prof. Lixin Gao

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object Oriented Programming (4) Prof. Lixin Gao

  2. Today’s Topics • Constructor • Static and Final • Organize multiple files/classes • Nesting Class • Java Package / Import Package • String Class • Exception/Throw

  3. 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

  4. 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( )

  5. 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

  6. 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

  7. 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

  8. Static, Final, and Public/Private • Static variable vs. Instance variable • Static method vs. method • Final variable • Final method • Public/Private variable/method

  9. 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

  10. 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); } }

  11. 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); } }

  12. 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.

  13. 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

  14. 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

  15. 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

  16. 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

  17. 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

  18. Employee Nested In Faculty Complete Example: FacultyNesting.java public class FacultyNesting { private class Employee { private name; private tel; … … } Employee emp; }

  19. 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.

  20. 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

  21. 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() ); } }

  22. 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() ); } }

  23. 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.*

  24. 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

  25. String class • Compare two Strings • Convert String to int • Convert int to String

  26. 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"); } }

  27. Why? • Now you will get surprising result: these two strings are not identical • What’s wrong?

  28. 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"); } }

  29. 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) )

  30. 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

  31. String to Int • Convert String to int • Integer.parseInt(strAge); • Example String strAge = “21”; int iAge; iAge = Integer.parseInt(strAge);

  32. Int to String • Convert int to String • Integer.toString(int); • Example int iScore = 89; String sScore; sScore = Integer.toString(iScore).

  33. 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

  34. 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

  35. 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)

  36. 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"); } } }

  37. Result For Exception Catch an exception at main function Press any key to continue . . . So this Exception e is an ArithmeticException

  38. 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

  39. Exception statement try { // some statements that may produce exceptions } catch (Exception e) { // handle exception object e } catch (AnotherException e) { // handle exception object e }

  40. 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); } }

  41. 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

  42. 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"); } }

  43. 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

  44. 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

More Related