Presentation is loading. Please wait.

Presentation is loading. Please wait.

SWE 510: Object Oriented Programming in Java1 Defining Classes 1 This slide set was compiled from the Absolute Java textbook and the instructor’s own class.

Similar presentations


Presentation on theme: "SWE 510: Object Oriented Programming in Java1 Defining Classes 1 This slide set was compiled from the Absolute Java textbook and the instructor’s own class."— Presentation transcript:

1 SWE 510: Object Oriented Programming in Java1 Defining Classes 1 This slide set was compiled from the Absolute Java textbook and the instructor’s own class materials.

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

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

4 SWE 510: Object Oriented Programming in Java4 Primitive Data Types versus Abstract 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; 10 a 20 b 10 data method( ) object1 20 data method( ) object2

5 SWE 510: Object Oriented Programming in Java5 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);

6 SWE 510: Object Oriented Programming in Java6 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/

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 SWE 510: Object Oriented Programming in Java8 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; } members Instance variables: (data members) Each object has its own values in these variables. Methods: Each object has the same methods (actions, computations).

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

10 SWE 510: Object Oriented Programming in Java10 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( ) ); } 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 myCourse1myCourse2 164.7 = 117.75 + 37.95 + 15 156.0 = 88.50 +67.50 + 0 instantiated department: CSS number: 161 section: A textPrice1: $111.75 textPrice2: $37.95 courseFee: $15 totalExpenditure( ) department: CSS number: 451 section: A textPrice1: $88.50 textPrice2: $67.50 courseFee: $0 totalExpenditure( ) myCourse1(CSS161A) needs $164.7 myCourse2(CSS451A) needs $156.0

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

12 The this Parameter this must 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 localinstance

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

21 SWE 510: Object Oriented Programming in Java21 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.javajavac CourseDemo.java javac CourseDemo.javajavac Course.java Compiled code Course.class CourseDemo.class Execution (from DOS/Linux command line.) java CourseDemo Start with the class name that includes main( ). Either order is fine. Compiling CourseDemo.java first automatically compiles Course.java, too.

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 type is 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 SWE 510: Object Oriented Programming in Java27 public and private Public Methods and instance variables accessible from outside of their class Private Methods and instance variables accessible within their class public type method1( ) { } public type method2( ) { } private type utility( ) { } public String department; public int number; private int enrollment; private int gradeAverage; public class Course css263.method1( ) css263.method2( ) css263.utility( ) css263.department css263.number css263.enrollment

28 SWE 510: Object Oriented Programming in Java28 Encapsulating Data in Class Which design is more secured from malicious attacks? public type method1( ) { } public type method2( ) { } private type utility( ) { } private String department; private int number; private int enrollment; private int gradeAverage; public class Course public type method1( ) { } public type method2( ) { } public type utility( ) { } public String department; public int number; public int enrollment; public int gradeAverage; public class Course css263.method1( ) css161.method1( ) css161.utility( ) css161.number = 263

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 SWE 510: Object Oriented Programming in Java34 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)

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 SWE 510: Object Oriented Programming in Java38 Nothing to return The same data type A variable, a constant, an expression, or an object Two kinds of methods Methods that only perform an action public void methodName( ) { /* body */ } Example public void writeOutput( ) { System.out.println(month + " " + day + ", " + year); } Methods that compute and return a result pubic type methodName( ) { /* body */ return a_value_of_type; } Example public double totalExpenditure( ) { return textPrice1 + textPrice2 + courseFee; } More About Methods

39 SWE 510: Object Oriented Programming in Java39 return Statement 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; }

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

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.


Download ppt "SWE 510: Object Oriented Programming in Java1 Defining Classes 1 This slide set was compiled from the Absolute Java textbook and the instructor’s own class."

Similar presentations


Ads by Google