Download constructor

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Choice modelling wikipedia , lookup

Transcript
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
1
Outline






Introduction/Overview
Constructors
Information Hiding
Overloading
Recursion
Homework!
Outline






Introduction/Overview
Constructors
Information Hiding
Overloading
Recursion
Homework!
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:
a
b
int a = 10, b = 20;
10
 Classes


20
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( );
object1
MyClass object2 = new MyClass( );
data
10
object1.data = 10;
object2
data
20
object2.data = 20;
method( )
SWE 510: Object Oriented Programming in Java
method( )
4
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
5
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
6
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
Members, Instance Variables, and
Methods
public class Course {
public String department;
public int number;
public char section;
public int enrollment;
public int limit;
public double textPrice1;
public double textPrice2;
public double courseFee;
//
//
//
//
//
//
//
//
SWE, IAS, CS, etc
course number
A, B, C ...
the current enrollment
max number of students
primary textbook
secondary textbook
laboratory fee
public int availableSpace( ) {
return limit - enrollment;
}
members
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.
Methods:
Each object has the
same methods
(actions, computations).
}
SWE 510: Object Oriented Programming in Java
8
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
9
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;
Multiple pieces of
public class Course {
public String department;
public int number;
public char section;
data public double textPrice1;
public double textPrice2;
public double courseFee;
Method
myCourse2.department = "CSS";
myCourse2.number = 451;
myCourse2.section = 'A';
myCourse2.textPrice1 = 88.50;
myCourse2.textPrice2 = 67.50;
myCourse2.courseFee = 0;
//
//
//
//
//
//
CSS, IAS, BUS, NRS, EDU
course number
A, B, C ...
primary textbook
secondary textbook
laboratory fee
public double totalExpenditure( ) {
return textPrice1 + textPrice2 + courseFee;
}
}
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
myCourse2
myCourse1
department: CSS
number: 451
section: A
textPrice1: $88.50
textPrice2: $67.50
courseFee: $0
totalExpenditure( )
156.0 = 88.50 +67.50 + 0
department: CSS
number: 161
section: A
textPrice1: $111.75
textPrice2: $37.95
courseFee: $15
totalExpenditure( )
164.7 = 117.75 + 37.95 + 15
myCourse1(CSS161A) needs $164.7
myCourse2(CSS451A) needs $156.0
SWE 510: Object Oriented Programming in Java
10
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

myInstanceVariable always means and is
always interchangeable with
this.myInstanceVariable
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
local
instance
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
Outline






Introduction/Overview
Constructors
Information Hiding
Overloading
Recursion
Homework!
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
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
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
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
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
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
public
public
public

String department;
int number;
char section;
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
20
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

Compiled code
javac CourseDemo.java
javac Course.java
Either order is fine. Compiling CourseDemo.java first
automatically compiles Course.java, too.
Course.class
CourseDemo.class

Execution (from DOS/Linux command line.)
java CourseDemo
Start with the class name that includes main( ).
SWE 510: Object Oriented Programming in Java
21
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 welldefined and simple interface
 In Java, hiding details is done by marking them
private
Outline






Introduction/Overview
Constructors
Information Hiding
Overloading
Recursion
Homework!
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
Encapsulation
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
public and private
 Public

Methods and instance variables
accessible from outside of their
css263.method1( )
class
public class Course
public type method1( ) {
}
css263.method2( )
 Private

public type method2( ) {
}
css263.utility( )
Methods and instance variables
accessible within their class
css263.department
css263.number
css263.enrollment
private type utility( ) {
}
public String department;
public int number;
private int enrollment;
private int gradeAverage;
SWE 510: Object Oriented Programming in Java
27
Encapsulating Data in Class
 Which design is more secured from malicious attacks?
public class Course
css161.method1( )
public type method1( ) {
public type method1( ) {
css263.method1( )
}
css161.utility( )
public class Course
}
public type method2( ) {
public type method2( ) {
}
}
public type utility( ) {
private type utility( ) {
}
}
css161.number = 263 public String department;
private String department;
public int number;
private int number;
public int enrollment;
private int enrollment;
public int gradeAverage;
private int gradeAverage;
SWE 510: Object Oriented Programming in Java
28
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
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
Outline






Introduction/Overview
Constructors
Information Hiding
Overloading
Recursion
Homework!
Overloading
 Overloading--two or more methods in the
same class have the same method name
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
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
34
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
Outline






Introduction/Overview
Constructors
Information Hiding
Overloading
Recursion
Homework!
Outline







Introduction/Overview
Constructors
Information Hiding
Overloading
Recursion
Homework!
Odds and Ends
More About Methods
 Two kinds of methods
 Methods that only perform an action
public void methodName( ) { /* body */ }

Example
Nothing to return
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
The same data type
A variable, a constant, an expression, or an object
public double totalExpenditure( ) {
return textPrice1 + textPrice2 + courseFee;
}
SWE 510: Object Oriented Programming in Java
38
return Statement
 Method to perform an action
 void Method( )
 Method to perform an action
 Return is not necessary but
 Return is necessary to return a
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” );
}
 type Method( )
value to a calling method.
 Example
public double totalExpenditure( ) {
return textPrice1 + textPrice2 + courseFee;
}
SWE 510: Object Oriented Programming in Java
39
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
40
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.