Class Definitions

Download Report

Transcript Class Definitions

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
1
Class and Objects
keyboard object
main( )
nextInt( )
next( )
nextLine( )
…
Scanner.class
Scanner keyboard = new Scanner( System.in );
instantiated
Scanner inFile = null;
try {
Scanner inFile = new Scanner( new FileInputStream( “data.txt” ) );
inFile object
} catch ( FileNotFoundException e ) {
System.exit( 0 );
nextInt( )
}
next( )
instantiated
int data1 = keyboard.nextInt( );
nextLine( )
String message = keyboard.nextLine( );
…
Int data2 = inFile.nextInt( );
String message = inFile.nextLine( );
nextInt( ) {
do some action
}
next( )
nextLine( )
…
123 how are you?
98765 yet alive!
CSS161: Fundamentals of Computing
2
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:
a
b
int a = 10, b = 20;
 Classes


10
20
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( );
object1
MyClass object2 = new MyClass( );
data
10
object1.data = 10;
object2
data
20
object2.data = 20;
method( )
CSS161: Fundamentals of Computing
method( )
3
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;
Multiple pieces of
myCourse2.department = "CSS";
myCourse2.number = 451;
myCourse2.section = 'A';
myCourse2.textPrice1 = 88.50;
myCourse2.textPrice2 = 67.50;
myCourse2.courseFee = 0;
public class Course {
public String department;
public int number;
public char section;
data public double textPrice1;
public double textPrice2;
public double courseFee;
Method
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
CSS161: Fundamentals of Computing
4
Members, Instance Variables, and
Methods
name
public class Course Class
{
public String department; //
public int number;
//
public char section;
//
public int enrollment;
//
public int limit;
//
public double textPrice1; //
public double textPrice2; //
public double courseFee;
//
CSS, IAS, BUS, NRS, EDU
course number
A, B, C ...
the current enrollment
the max number of students
primary textbook
Instance variables:
secondary textbook
(data members)
laboratory fee
Each object has its own
values in these variables.
public int availableSpace( ) {
return limit - enrollment;
}
members
public double capacity( ) {
return ( double )enrollment / limit;
Methods:
}
Each object has the same methods
(actions, computations).
public double totalExpenditure( ) {
return textPrice1 + textPrice2 + courseFee;
}
}
CSS161: Fundamentals of Computing
5
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
6
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 + ")" );
CSS161: Fundamentals of Computing
7
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
}
Public: accessible from any other methods (including main( ))
Private: accessible from a method within the same class
 Example
public double totalExpenditure( ) {
return textPrice1 + textPrice2 + courseFee;
If a method takes only a certain action, this should be void
}
and “return” is unnecessary.
 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
8
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
An either way is fine. Compiling CourseDemo.java first
automatically compile Course.java, too.
Course.class
CourseDemo.class

Execution (from DOS/Linux command line.)
java CourseDemo
Start with the class name that includes main( ).
CSS161: Fundamentals of Computing
9
Textbook Example - 4.1
public class DateFirstTry
{
public String month;
public int day;
public int year; //a four digit number.
public void writeOutput( )
{
System.out.println(month + " " + day +
", " + year);
}
}
date1:
December 31, 2007
date2:
July 4, 1776
public class DateFirstTryDemo
{
public static void main(String[] args)
{
DateFirstTry date1, date2;
date1 = new DateFirstTry( );
date2 = new DateFirstTry( );
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( );
}
}
CSS161: Fundamentals of Computing
10
Self-Test Exercises
 Work on textbook p170’s exercises 1 ~ 2.
CSS161: Fundamentals of Computing
11
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;
}
CSS161: Fundamentals of Computing
12
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;
}
CSS161: Fundamentals of Computing
13
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
14
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;
CSS161: Fundamentals of Computing
15
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;
CSS161: Fundamentals of Computing
16
Textbook Example - 4.2
import java.util.Scanner;
public class DateSecondTry
{
private String month;
private int day;
private int year; //a four digit number.
public void writeOutput( )
{
System.out.println(month + " " + day + ", " + year);
}
public void readInput( )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter month, day, and year.");
System.out.println("Do not use a comma.");
month = keyboard.next( );
day = keyboard.nextInt( );
year = keyboard.nextInt( );
}
public int getDay( )
{
return day;
}
public int getYear( )
{
return year;
}
public int 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
}
}
}
CSS161: Fundamentals of Computing
17
Textbook Example - 4.3
public class DemoOfDateSecondTry
{
public static void main(String[] args)
{
DateSecondTry date = 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
18
Self-Test Exercises
 Work on textbook p176’s exercise 3
CSS161: Fundamentals of Computing
19