1 / 41

Defining Classes 1

Defining Classes 1. This slide set was compiled from the Absolute Java textbook and the instructor’s own class materials. Outline. Introduction/Overview Constructors Information Hiding Overloading Recursion Homework!. Outline. Introduction/Overview Constructors Information Hiding

Télécharger la présentation

Defining Classes 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 1 This slide set was compiled from the Absolute Java textbook and the instructor’s own class materials. SWE 510: Object Oriented Programming in Java

  2. Outline • Introduction/Overview • Constructors • Information Hiding • Overloading • Recursion • Homework!

  3. Outline • Introduction/Overview • Constructors • Information Hiding • Overloading • Recursion • Homework!

  4. b 20 a 10 object1 object2 data data 10 20 method( ) method( ) Primitive Data Types versusAbstract Data Types (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 defined before their use (“instantiation”) • 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; SWE 510: Object Oriented Programming in Java

  5. Primitive Data Types versus Classes—comparison • “Primitive” data type (String is not primitive in java, but to some extent we can treat it like one) • String can be used like a primitive data type String myString; myString = “test string”; String myString = “test string”; String myString = someOtherString; • Abstract data type (class) • The String class is much more powerful than a primitive type String myString = new String (“test string”); myString.length(); myString.valueOf(); myString.equals(someOtherString); myString.compareTo(someOtherString); myString.split(regularExpression); SWE 510: Object Oriented Programming in Java

  6. Java Doc • Google • Use Google to locate the particular class or language feature of interest • Dive Straight in • Go straight to the Java documentation • http://download.oracle.com/javase/6/docs/ • http://download.oracle.com/javase/6/docs/api/ SWE 510: Object Oriented Programming in Java

  7. The Contents of a Class Definition • A class definition specifies the data items and methods that all of its objects will have • These data items and methods are sometimes called members of the object • Data items are called fields or instance variables • Instance variable declarations and method definitions can be placed in any order within the class definition • Methods define an object’s behavior

  8. Members, Instance Variables, and Methods public class Course { public String department; // SWE, IAS, CS, etc public int number; // course number public char section; // A, B, C ... public int enrollment; // the current enrollment public int limit; // 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). SWE 510: Object Oriented Programming in Java

  9. 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( ); SWE 510: Object Oriented Programming in Java

  10. 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 Instantiation--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 SWE 510: Object Oriented Programming in Java

  11. The this Parameter • All instance variables are understood to have <the calling object>. in front of them • If an explicit name for the calling object is needed, the keyword this can be used • myInstanceVariablealways means and is always interchangeable with this.myInstanceVariable

  12. The this Parameter • thismust be used if a parameter or other local variable with the same name is used in the method • Otherwise, all instances of the variable name will be interpreted as local int someVariable = this.someVariable local instance

  13. The this Parameter • The this parameter is a kind of hidden parameter • Even though it does not appear on the parameter list of a method, it is still a parameter • When a method is invoked, the calling object is automatically plugged in for this • A Constructor has a this Parameter

  14. Outline • Introduction/Overview • Constructors • Information Hiding • Overloading • Recursion • Homework!

  15. Constructors • A constructor is a special kind of method that is designed to initialize the instance variables for an object: Public ClassName(anyParameters){code} • A constructor must have the same name as the class • A constructor has no type returned, not even void • Constructors are typically overloaded

  16. Constructors • A constructor is called when an object of the class is created using new: ClassName objectName = new ClassName(anyArgs); • The name of the constructor and its parenthesized list of arguments (if any) must follow the new operator • This is the only valid way to invoke a constructor: a constructor cannot be invoked like an ordinary method • If a constructor is invoked again (using new), the first object is discarded and an entirely new object is created • If you need to change the values of instance variables of the object, use mutator methods instead

  17. You Can Invoke Another Method in a Constructor • The first action taken by a constructor is to create an object with instance variables • Therefore, it is legal to invoke another method within the definition of a constructor, since it has the newly created object as its calling object • For example, mutator methods can be used to set the values of the instance variables • It is even possible for one constructor to invoke another

  18. Include a No-Argument Constructor • If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created • If you include even one constructor in your class, Java will not provide this default constructor • If you include any constructors in your class, be sure to provide your own no-argument constructor as well

  19. Default Variable Initializations • Instance variables are automatically initialized in Java • boolean types are initialized to false • Other primitives are initialized to the zero of their type • Class types are initialized to null • However, it is a better practice to explicitly initialize instance variables in a constructor • Note: Local variables are not automatically initialized

  20. 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 + ")" ); SWE 510: Object Oriented Programming in Java

  21. 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 Either order is fine. Compiling CourseDemo.java first automatically compiles Course.java, too. Start with the class name that includes main( ). SWE 510: Object Oriented Programming in Java

  22. Information Hiding and Encapsulation • Information hiding is the practice of separating how to use a class from the details of its implementation • Abstraction is another term used to express the concept of discarding details in order to avoid information overload • Encapsulation means that the data and methods of a class are combined into a single unit (i.e., a class object), which hides the implementation details • Knowing the details is unnecessary because interaction with the object occurs via a well-defined and simple interface • In Java, hiding details is done by marking them private

  23. Outline • Introduction/Overview • Constructors • Information Hiding • Overloading • Recursion • Homework!

  24. A Couple of Important Acronyms: API and ADT • The API or application programming interface for a class is a description of how to use the class • A programmer need only read the API in order to use a well designed class • An ADT or abstract data typeis a data type that is written using good information-hiding techniques

  25. Encapsulation

  26. public and private Modifiers • The modifier public means that there are no restrictions on where an instance variable or method can be used • The modifier private means that an instance variable or method cannot be accessed by name outside of the class • It is considered good programming practice to make all instance variables private • Most methods are public, and thus provide controlled access to the object • Usually, methods are private only if used as helping methods for other methods in the class

  27. 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 SWE 510: Object Oriented Programming in Java

  28. 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; SWE 510: Object Oriented Programming in Java

  29. Accessor and Mutator Methods • Accessor methods allow the programmer to obtain the value of an object's instance variables • The data can be accessed but not changed • The name of an accessor method typically starts with the word get • Mutator methods allow the programmer to change the value of an object's instance variables in a controlled manner • Incoming data is typically tested and/or filtered • The name of a mutator method typically starts with the word set

  30. Mutator Methods Can Return a Boolean Value • Some mutator methods issue an error message and end the program whenever they are given values that aren't sensible • An alternative approach is to have the mutator test the values, but to never have it end the program • Instead, have it return a boolean value, and have the calling program handle the cases where the changes do not make sense

  31. Outline • Introduction/Overview • Constructors • Information Hiding • Overloading • Recursion • Homework!

  32. Overloading • Overloading--two or more methods in the same class have the same method name

  33. Overloading--Rules • All definitions of the method name must have different signatures • A signature consists of the name of a method together with its parameter list • Differing signatures must have different numbers and/or types of parameters • The signature does not include the type returned • Java does not permit methods with the same signature and different return types in the same class

  34. Overloading—example • Familiar overloaded method System.out.println() System.out.println(boolean) System.out.println(char) System.out.println(char[]) System.out.println(double) System.out.println(float) System.out.println(int) System.out.println(long) System.out.println(java.lang.Object) System.out.println(java.lang.String) SWE 510: Object Oriented Programming in Java

  35. Overloading and Automatic Type Conversion • If Java cannot find a method signature that exactly matches a method invocation, it will try to use automatic type conversion • The interaction of overloading and automatic type conversion can have unintended results • In some cases of overloading, because of automatic type conversion, a single method invocation can be resolved in multiple ways • Ambiguous method invocations will produce an error in Java

  36. Outline • Introduction/Overview • Constructors • Information Hiding • Overloading • Recursion • Homework!

  37. Outline • Introduction/Overview • Constructors • Information Hiding • Overloading • Recursion • Homework! • Odds and Ends

  38. 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; } SWE 510: Object Oriented Programming in Java

  39. 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 SWE 510: Object Oriented Programming in Java

  40. 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(); SWE 510: Object Oriented Programming in Java

  41. Methods That Return a Boolean Value • An invocation of a method that returns a value of type boolean returns either true or false • Therefore, it is common practice to use an invocation of such a method to control statements and loops where a Boolean expression is expected • if-else statements, while loops, etc.

More Related