1 / 19

Defining Classes - Day 1

Defining Classes - Day 1. This slide set was compiled from the Absolute Java textbook slides (Walter Savitch) and the professor’s own class materials. keyboard object. nextInt( ) next( ) nextLine( ) …. inFile object. nextInt( ) next( ) nextLine( ) …. Class and Objects. main( ).

corlew
Télécharger la présentation

Defining Classes - Day 1

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. Defining Classes - Day 1 This slide set was compiled from the Absolute Java textbook slides (Walter Savitch) and the professor’s own class materials. CSS161: Fundamentals of Computing

  2. keyboard object nextInt( ) next( ) nextLine( ) … inFile object nextInt( ) next( ) nextLine( ) … Class and Objects main( ) Scanner.class Scanner keyboard = new Scanner( System.in ); Scanner inFile = null; try { Scanner inFile = new Scanner( new FileInputStream( “data.txt” ) ); } catch ( FileNotFoundException e ) { System.exit( 0 ); } int data1 = keyboard.nextInt( ); String message = keyboard.nextLine( ); Int data2 = inFile.nextInt( ); String message = inFile.nextLine( ); instantiated nextInt( ) { do some action } next( ) nextLine( ) … instantiated 123 how are you? 98765 yet alive! CSS161: Fundamentals of Computing

  3. b 20 a 10 object1 object2 data data 10 20 method( ) method( ) Primitive Data Types versus Classes • Primitive data types • a single piece of data • byte, char, short, int, long, float, double, boolean • Variables declared before their use: int a = 10, b = 20; • Classes • a collection of multiple pieces of data + methods • Objects instantiated before their use • Including the same methods • Including the same set of data, but • Maintaining different values in each piece of data MyClass object1 = new MyClass( ); MyClass object2 = new MyClass( ); object1.data = 10; object2.data = 20; CSS161: Fundamentals of Computing

  4. public class Course { public String department; // CSS, IAS, BUS, NRS, EDU public int number; // course number public char section; // A, B, C ... public double textPrice1; // primary textbook public double textPrice2; // secondary textbook public double courseFee; // laboratory fee public double totalExpenditure( ) { return textPrice1 + textPrice2 + courseFee; } } Multiple pieces of data Method myCourse2 myCourse1 Class Example public class CourseDemo { public static void main( String[] args ) { Course myCourse1 = new Course( ); Course myCourse2 = new Course( ); myCourse1.department = "CSS"; myCourse1.number = 161; myCourse1.section = 'A'; myCourse1.textPrice1 = 111.75; myCourse1.textPrice2 = 37.95; myCourse1.courseFee = 15; myCourse2.department = "CSS"; myCourse2.number = 451; myCourse2.section = 'A'; myCourse2.textPrice1 = 88.50; myCourse2.textPrice2 = 67.50; myCourse2.courseFee = 0; System.out.println( "myCourse1(" + myCourse1.department + myCourse1.number + myCourse1.section + ") needs $" + myCourse1.totalExpenditure( ) ); System.out.println( "myCourse2(" + myCourse2.department + myCourse2.number + myCourse2.section + ") needs $" + myCourse2.totalExpenditure( ) ); } } instantiated instantiated department: CSS number: 451 section: A textPrice1: $88.50 textPrice2: $67.50 courseFee: $0 totalExpenditure( ) department: CSS number: 161 section: A textPrice1: $111.75 textPrice2: $37.95 courseFee: $15 totalExpenditure( ) 164.7 = 117.75 + 37.95 + 15 156.0 = 88.50 +67.50 + 0 myCourse1(CSS161A) needs $164.7 myCourse2(CSS451A) needs $156.0 CSS161: Fundamentals of Computing

  5. Members, Instance Variables, and Methods Class name public class Course { public String department; // CSS, IAS, BUS, NRS, EDU public int number; // course number public char section; // A, B, C ... public int enrollment; // the current enrollment public int limit; // the max number of students public double textPrice1; // primary textbook public double textPrice2; // secondary textbook public double courseFee; // laboratory fee public int availableSpace( ) { return limit - enrollment; } public double capacity( ) { return ( double )enrollment / limit; } public double totalExpenditure( ) { return textPrice1 + textPrice2 + courseFee; } } Instance variables: (data members) Each object has its own values in these variables. members Methods: Each object has the same methods (actions, computations). CSS161: Fundamentals of Computing

  6. Object Instantiation with new • Declare a reference variable (a box that contains a reference to a new instance.) ClassName object; • object has no reference yet, (= null). • Create a new instance from a given class. object = new ClassName( ); • object has a reference to a new instance. • Declare a reference variable and initialize it with a reference to a new instance created from a given class ClassName object = new ClassName( ); CSS161: Fundamentals of Computing

  7. Accessing Instance Variables • Declaring an instance variable in a class • public type instanceVariable; // accessible from any methods (main( )) • private type instanceVariable; // accessible from methods in the same class • Examples: public String department; public int number; public char section; public int enrollment; • Assigning a value to an instance variable of a given object • objectName.instanceVariable = expression; • Examples: myCourse1.department = "CSS"; myCourse1.number = 161; myCourse1.section = 'A'; myCourse1.enrollment = 24; • Reading the value of an instance of a given object • Operator objectName.instanceVariable operator • Example: System.out.println( "myCourse1 = " + myCourse1.department + myCourse1.number + ")" ); CSS161: Fundamentals of Computing

  8. Public: accessible from any other methods (including main( )) Private: accessible from a method within the same class If a method takes only a certain action, this should be void and “return” is unnecessary. Defining and Accessing Methods • Defining a method in a class public type method( ) { // heading // method body //code to perform some action and/or compute a value } • Example public double totalExpenditure( ) { return textPrice1 + textPrice2 + courseFee; } • Accessing a method in a class objectName.method( ); • Example System.out.println( "myCourse1(" + myCourse1.department + myCourse1.number + myCourse1.section + ") needs $" + myCourse1.totalExpenditure( ) ); CSS161: Fundamentals of Computing

  9. Class Names and Files • Each class should be coded in a separate file whose name is the same as the class name + .java postfix. • Example • Source code Course.java CourseDemo.java • Compilation (from DOS/Linux command line.) javac Course.java javac CourseDemo.java javac CourseDemo.java javac Course.java • Compiled code Course.class CourseDemo.class • Execution (from DOS/Linux command line.) java CourseDemo An either way is fine. Compiling CourseDemo.java first automatically compile Course.java, too. Start with the class name that includes main( ). CSS161: Fundamentals of Computing

  10. Textbook Example - 4.1 public classDateFirstTry { publicStringmonth; publicintday; publicintyear; //a four digit number. publicvoidwriteOutput( ) { System.out.println(month + " " + day + ", " + year); } } public classDateFirstTryDemo { public static void main(String[] args) { DateFirstTrydate1, date2; date1 = newDateFirstTry( ); date2 = newDateFirstTry( ); date1.month = "December"; date1.day = 31; date1.year = 2007; System.out.println("date1:"); date1.writeOutput( ); date2.month = "July"; date2.day = 4; date2.year = 1776; System.out.println("date2:"); date2.writeOutput( ); } } date1: December 31, 2007 date2: July 4, 1776 CSS161: Fundamentals of Computing

  11. Self-Test Exercises • Work on textbook p170’s exercises 1 ~ 2. CSS161: Fundamentals of Computing

  12. Nothing to return The same data type A variable, a constant, an expression, or an object More About Methods • Two kinds of methods • Methods that only perform an action public void methodName( ) { /* body */ } • Example publicvoidwriteOutput( ) { System.out.println(month + " " + day + ", " + year); } • Methods that compute and return a result pubic type methodName( ) { /* body */ return a_value_of_type; } • Example publicdouble totalExpenditure( ) { return textPrice1 + textPrice2 + courseFee; } CSS161: Fundamentals of Computing

  13. Method to perform an action void Method( ) Return is not necessary but may be added to end the method before all its code is ended Example public void writeMesssage( ) { System.out.println( “status” ); if ( ) { System.out.println( “nothing” ); return; } else if ( error == true ) System.out.print( “ab” ); System.out.println( “normal” ); } Method to perform an action type Method( ) Return is necessary to return a value to a calling method. Example public double totalExpenditure( ) { return textPrice1 + textPrice2 + courseFee; } return Statement CSS161: Fundamentals of Computing

  14. Any Method Can Be Used As a void Method • A method that returns a value can also perform an action • If you want the action performed, but do not need the returned value, you can invoke the method as if it were a void method, and the returned value will be discarded: objectName.returnedValueMethod(); CSS161: Fundamentals of Computing

  15. public and private • Public • Methods and instance variables accessible from outside of their class • Private • Methods and instance variables accessible within their class public class Course css263.method1( ) public type method1( ) { } css263.method2( ) public type method2( ) { } css263.utility( ) private type utility( ) { } css263.department public String department; public int number; private int enrollment; private int gradeAverage; css263.number css263.enrollment CSS161: Fundamentals of Computing

  16. Encapsulating Data in Class • Which design is more secured from malicious attacks? public class Course public class Course public type method1( ) { } public type method1( ) { } css161.method1( ) css263.method1( ) public type method2( ) { } public type method2( ) { } css161.utility( ) public type utility( ) { } private type utility( ) { } css161.number = 263 public String department; public int number; public int enrollment; public int gradeAverage; private String department; private int number; private int enrollment; private int gradeAverage; CSS161: Fundamentals of Computing

  17. Textbook Example - 4.2 publicint getMonth( ) { if (month.equalsIgnoreCase("January")) return 1; else if (month.equalsIgnoreCase("February")) return 2; else if (month.equalsIgnoreCase("March")) return 3; else if (month.equalsIgnoreCase("April")) return 4; else if (month.equalsIgnoreCase("May")) return 5; else if (month.equals("June")) return 6; else if (month.equalsIgnoreCase("July")) return 7; else if (month.equalsIgnoreCase("August")) return 8; else if (month.equalsIgnoreCase("September")) return 9; else if (month.equalsIgnoreCase("October")) return 10; else if (month.equalsIgnoreCase("November")) return 11; else if (month.equalsIgnoreCase("December")) return 12; else { System.out.println("Fatal Error"); System.exit(0); return 0; //Needed to keep the compiler happy } } } import java.util.Scanner; public classDateSecondTry { privateString month; privateintday; privateint year; //a four digit number. publicvoid writeOutput( ) { System.out.println(month + " " + day + ", " + year); } publicvoid readInput( ) { Scannerkeyboard = newScanner(System.in); System.out.println("Entermonth, day, and year."); System.out.println("Do not use a comma."); month = keyboard.next( ); day = keyboard.nextInt( ); year = keyboard.nextInt( ); } publicint getDay( ) { return day; } publicint getYear( ) { return year; } CSS161: Fundamentals of Computing

  18. Textbook Example - 4.3 public classDemoOfDateSecondTry { public staticvoidmain(String[] args) { DateSecondTrydate = new DateSecondTry( ); date.readInput( ); int dayNumber = date.getDay( ); System.out.println("That is the" + dayNumber + "th day of the month."); } } Enter month, day, and year. Do not use a comma. July 4 1776 That is the 4th day of the month CSS161: Fundamentals of Computing

  19. Self-Test Exercises • Work on textbook p176’s exercise 3 CSS161: Fundamentals of Computing

More Related