CS 2110 Lecture Notes - Lecture 4: Class Variable, Local Variable

12 views5 pages
Published on 16 Mar 2017
School
Cornell University
Department
Computer Science
Course
CS 2110
Professor
Lecture 4 - Class Hierarchy
Review - Big Ideas
Type: A set of values and operations on them (L1)
(int: +, -, *, /, %, etc.)
Classes define new types (L2)
A note on method specifications
Method specs SHOULD NOT mention fields
Why? Because the fields are hidden
So why not just make the fields
public?
Because you might have different
as of ostrutig e istaes of the lass that do’t use
certain fields
So for getHour(), if we construct the
class using only minutes, then there is no hour field!
Today: Class W (for Worker)
Methods:
Public W(String n, int s, W b)
Constructor with name n, Ssn s, Boss b
Public String getLname()
Returns Last Name
Public String getSsn()
Returns last 4 digits of Ssn
Public W getBoss()
Returns Boss
Public void setBoss(W b)
Changes Boss to b
So if these are our only methods, what happens if we try to use
toString()?
It by default returns the id stored in
our object
Ex: W Prez = ew WMartiez,
123456789, null);
Prez.toString() returns the id of the
object stored in Prez!!
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in
But if e hae’t ipleeted a ethod toString(), how
could this be possible!
No matter our class, the Class Object
is a superclass for all of them, the superest class
Has some default methods, like toString()
Inheritance of superclasses
This needs to designed to make sense
Do’t just use eteds to get hidde eers
So if class A extends B, A SHOULD BE AN ACTUAL PHYSICAL EXTENSION
OF B
Example: Elephant would extend
Animal
Example
Triangle extends Shape
PHDTester DOES NOT EXTEND PHD
It is’t a tpe of PHD
When I say type right now, I mean like an
example
BankAccount DOES NOT EXTEND CheckingAccount
Other way around works
So what methods exist in Class Object?
toString()
Returns the name of the object
The name of the folder holding the object
For example, for Worker Prez, if the folder storing the
object for Prez is called W@2a4, then Prez.toString()
returns W@2a4!
BUT, we can override the definition of a method of a superclass
Say we define WITHIN THE CLASS W:
public String toString() {
return Worker  + lastNae +  has ““N ???-??-
+ get“s + ad boss  + boss;
Now, if we call Prez.toString() we
get
Worker Martinez has SSN ???-??- and boss null”
That’s prett dad!
No it’s kida aoig to hae it
sa “boss null”
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 5 pages and 3 million more documents.

Already have an account? Log in