Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Defining New Classes in CMPU-101: Problem-Solving and Abstraction at Vassar College - Prof, Assignments of Computer Science

This chapter from the cmpu-101 course at vassar college introduces students to defining new classes, specifically focusing on the 'driver' class and its role in creating objects and sending messages. The document also covers the concept of overloading methods and naming constructor parameters. Students will learn about the structure of classes, instance variables, constructors, and methods, as well as the importance of using descriptive variable names.

Typology: Assignments

Pre 2010

Uploaded on 08/16/2009

koofers-user-1sh-1
koofers-user-1sh-1 🇺🇸

10 documents

1 / 9

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 6
Defining New Classes
CMPU-101: Problem-Solving and Abstraction
Marc Smith
Vassar College
Spring 2007
2
Recap
Chapter 3
Using predefined classes & objects
System.out.println("hello");
Chapters 4 & 5
Define instances of predefined classes
String s = "hello".toUpperCase();
Scanner sc = new Scanner(System.in);
Now…
Define new classes
3
Prog0601 — Driver
Driver refers to code, commonly found in the main method, that creates
objects and sends them messages to get the program work started.
What do these statements tell us about class Teacher?
Teacher t = new Teacher();
t.lecture();
Teacher has a “zero-parameter” constructor and a method
called lecture with prototype void lecture()
4
Prog0601 — class Teacher
//-------------------------------------------------------------
public Teacher() {}
//-------------------------------------------------------------
public void lecture()
{
System.out.println("do your homework!");
}
//-------------------------------------------------------------
5
Style Used in the Text
Classes are separated by
///////////////////////////////////////////
Methods are surrounded by
//-----------------------------------------
Classes end with
} // end class className
6
Prog0602 — Overload the lecture Method
public void lecture ( String name )
{
System.out.println
( name + ", do your homework!");
}
This version of lecture takes a single String parameter
The prototype of this method is void lecture(String)
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Defining New Classes in CMPU-101: Problem-Solving and Abstraction at Vassar College - Prof and more Assignments Computer Science in PDF only on Docsity!

Chapter 6

Defining New Classes

CMPU-101: Problem-Solving and Abstraction Marc Smith Vassar College Spring 2007 2

Recap

Chapter 3 Using predefined classes & objects System.out.println("hello"); Chapters 4 & 5 Define instances of predefined classes String s = "hello".toUpperCase(); Scanner sc = new Scanner(System.in); Now… Define new classes 3

Prog 0601 — Driver

Driver refers to code, commonly found in the main method, that creates objects and sends them messages to get the program work started. What do these statements tell us about class Teacher? Teacher t = new Teacher(); t.lecture(); Teacher has a “zero-parameter” constructor and a method called lecture with prototype void lecture() 4

Prog 0601 — class Teacher

public Teacher() {} //------------------------------------------------------------- public void lecture() { System.out.println("do your homework!"); } //-------------------------------------------------------------

Style Used in the Text

Classes are separated by /////////////////////////////////////////// Methods are surrounded by //----------------------------------------- Classes end with } // end class className

Prog 0602 — Overload the lecture Method

public void lecture ( String name ) { System.out.println ( name + ", do your homework!"); } This version of lecture takes a single String parameter The prototype of this method is void lecture(String)

7

Tip Revisited

When testing features of a new language, make a minimal change to a working program. Starting with a blank template file ensures that you start with a working program. 8

class Animal in UML Notation

Animal

void speak()

String name

String sound

instance variables methods 9

Prog 0603 — Driver

Animal a1 = new Animal("fluffy","meow"); a1.speak(); Animal a2 = new Animal("fido","woof"); a2.speak(); Animal a3 = a2; a3.speak(); a1 = new Animal("bessie","moo"); a1.speak(); The Driver creates three variables of type Animal: a1, a2, and a3. 10 Animal a1 = new Animal("fluffy","meow"); fluffy meow a Animal a2 = new Animal("fido","woof"); fluffy meow a fido woof a

fluffy

meow

a

fido

woof

a

a

Animal a3 = a2;

19 Animal a1 = new Animal("fluffy","meow"); a1.speak(); Animal a2 = new Animal("fido","woof"); a2.speak(); Animal a3 = a2; a3.speak(); a1 = new Animal("bessie","moo"); a1.speak(); What is the output from this snippet of code? 20

In-Class Exercise

Write public void sleeps() so that a1.sleeps(); prints out fluffy is sleeping 21

In-Class Exercise

Write public void twice() so that a1.twice(); prints out meow, meow 22 Naming Constructor Parameters Stylistic Considerations (1) public Animal ( String theName, String theSound ) { name = theName; sound = theSound; } public Animal ( String name_, String sound_ ) { name = name_; sound = sound_; } Naming Constructor Parameters Stylistic Considerations (2) public Animal ( String a, String b ) { name = a; sound = b; } Naming Constructor Parameters Stylistic Considerations (3) a and b are Bad Variable Names (BVN) because they are non-descriptive

25 public Animal ( String name, String sound ) { this.name = name; this.sound = sound; } The winner! (this is the style we will adopt in this course) Naming Constructor Parameters Stylistic Considerations (4) 26

The this Pointer

For a constructor, this refers to the instance being constructed. For any other method, this refers to the receiver of the message. ! instance = instance of a class = object 27

Getters — Accessors

public String getSound() { return this.sound; } Methods intended to return the value of an instance variable In general, these methods have no parameters and a non-void return type 28

Setters — Mutators

public void setSound ( String newSound ) { this.sound = newSound; } Methods intended to set the value of an instance variable In general, these methods have a void return type and a single parameter. User-Defined Classes as Parameters public void chases ( Animal target ) { System.out.println ( this.name + " is chasing " + target.name ); } Objects of a particular type can receive messages containing parameters that are other objects of the same type.

User-Defined Class as a Return Type

receiver values result values name sound name sound "fido" "woof" "big fido" "WOOF" "fluffy" "meow" "big fluffy" "MEOW" Method makeBig

37 Let's make System.out.println(new Animal("fido","woof"); print out fido (woof) We need to write a toString method for class Animal. 38

Prog 0610 — toString

public String toString() { return name + " (" + sound + ")"; } 39

toString is used by

println System.out.println(a1); System.out.println(new Animal("leo","roar")); concatenation (+) System.out.println("I think that " + a1 + " is more faithful than " + a2 + "."); 40 Reading an Object from the Keyboard We want the dialog: Reading an Animal ... Enter name: fido Enter sound: woof See Prog0611.

static read Method

public static Animal read ( PrintStream ps, Scanner sc ) { ps.println("Reading an Animal ..."); ps.print("Enter name: "); String name = sc.nextLine(); ps.print("Enter sound: "); String sound = sc.nextLine(); return new Animal(name,sound); }

Calling a static read Method

Scanner kb = new Scanner(System.in); Animal a = Animal.read(System.out,kb); System.out.println(); System.out.println(a);

43

Instance Method vs Class Method

instance method class method (static method) called by tacking to the right of an instance of the class called by tacking to the right of the class name requires an instance of the class does not require an instance of the class 44

Prog 0612 — Reading from a File

System.out.print("Enter the name of a file of Animals: "); String filename = kb.nextLine(); Scanner sc = new Scanner(new File(filename)); Animal a1 = Animal.read(System.out,sc); Animal a2 = Animal.read(System.out,sc); Prompts are unnecessary for this case! 45

static Methods in Class Math

Math.abs(…) Math.sin(…) Math.sqrt(…) 46

public static void main

We need to be able to call the main method even though we haven't created an instance of the driver class. This requires that main be static. (Why must main be public?) ! How do we call the main method? (hint: In DrJava, from the interactions pane, how do you run a program that has a main method?)

static Methods Can't Refer to Instance Variables

class A { private int var; //----------------------------------------------------------------------- public static void f() { System.out.println(this.var);! Note instance variable! } //----------------------------------------------------------------------- } This won't compile! ! If you follow our rule of referring to instance variables using this, you should never see a static method that contains a this!

Sharing Data Structure

Animal a1 = new Animal("fluffy","meow"); Animal a2 = a1; // Beware! // Memory structure is // being shared. a1.speak(); a2.speak(); a2.setName("pretzel"); System.out.println(); a1.speak(); a2.speak(); In other words, a1 and a Both refer to the same Animal object in memory! Draw the picture…