36
Lecture 14: Introduction to Classes and Objects CS201

Lecture 14: Introduction to Classes and Objects CS201

  • View
    230

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lecture 14: Introduction to Classes and Objects CS201

Lecture 14:

Introduction to Classes and Objects

CS201

Page 2: Lecture 14: Introduction to Classes and Objects CS201

Abstraction

2

Some definitions of

Abstract (adjective):•Considered apart from any application to a particular object; removed from; apart from; separate; abstracted.  •Apart from practice or reality; not concrete; ideal; vague; theoretical; impersonal.•(art) Free from representational qualities.•(logic) General (as opposed to particular).  •Synonyms

– (not applied or practical): conceptual, theoretical– (insufficiently factual): formal

- Source: Wiktionary

Page 3: Lecture 14: Introduction to Classes and Objects CS201

Abstraction

3

• Abstraction can be multi-layered– A manhole cover is a round thing that covers a

manhole to prevent people from falling in– A round thing is a physical object that has the

quality of being round– Round means “in the shape of a circle”– A circle is a geometric shape defined by a set of

points which are equidistant from the center

– Why are manhole covers round?

Page 4: Lecture 14: Introduction to Classes and Objects CS201

Abstraction

4

• Abstraction is a key concept in programming• Programmers sometimes use the word

“abstract” as a transitive verb meaning “to create an abstraction of,” as well as the more common English usage of “abstract” as an adjective

Page 5: Lecture 14: Introduction to Classes and Objects CS201

Object Oriented Programming

5

• The coding we have done so far is procedural programming• OOP is built on the foundation of

procedural programming• Object Oriented Programming is the

current state of the art in creating modular code• CS202 will focus on OOP

Page 6: Lecture 14: Introduction to Classes and Objects CS201

Objects

6

• Objects contain both data and methods that are designed to work on the object’s data

• In Java, objects are instances of classes• Classes are more abstract than objects–A class defines the data types and methods

for objects–An object contains data

Page 7: Lecture 14: Introduction to Classes and Objects CS201

Account Class

7

public class Account { protected double balance; protected Customer customer;public Account( Customer customerIn, double amount ) {

customer = customerIn;balance = amount;

} public void deposit( double amount ) {

balance += amount; } public double withdraw( double amount ) {

if (balance >= amount) { balance -= amount; return amount;

} else return 0.0; } public double getbalance() {

return balance; }

}

Page 8: Lecture 14: Introduction to Classes and Objects CS201

Classes

8

• We create an object by instantiating a class• You have already done this with code

like this:–Classname objectname = new Classname()– For example,• Scanner sc = new Scanner();

Page 9: Lecture 14: Introduction to Classes and Objects CS201

Static vs NonStatic Methods

9

• Static methods like main() can be run using the class code without instantiating an object• All other methods can be run only as

methods of objects instantiated from the class:–sc.nextDouble();

Page 10: Lecture 14: Introduction to Classes and Objects CS201

Classes

10

public class Archimedes{public static void main(String[] args){

Archimedes arch = new Archimedes();arch.sayHi();

}

private void sayHi(){System.out.println("HI!");

}}

Page 11: Lecture 14: Introduction to Classes and Objects CS201

Constructors

11

• Constructors are methods that populate data fields or does other work when an object is created

• Every class has a default constructor that takes no parameters and doesn’t do anything

• You can also write your own constructors• Method header looks like this:

public ClassName(parameters){}• A class may have more than one constructor

(“constructor overloading”)• By convention, constructors are the first methods

listed in a class.

Page 12: Lecture 14: Introduction to Classes and Objects CS201

Constructors

12

public class Archimedes{private String message;

public Archimedes(String messageIn){message = messageIn;

}

public static void main(String[] args){Archimedes arch = new Archimedes("Hi!");arch.say();

}

private void say(){System.out.println(message);

}}

Page 13: Lecture 14: Introduction to Classes and Objects CS201

Why don’t we just use static methods for everything?

13

public class Clone{private String name;

public Clone(String nameIn){name = nameIn;

}

public static void main(String[] args){

Clone bob = new Clone("Bob");Clone joe = new Clone("Joe");Clone mary = new Clone("Mary");

bob.greet();joe.greet();mary.greet();

}

private void greet(){System.out.println("Hi, my name is " + name);

}}

Page 14: Lecture 14: Introduction to Classes and Objects CS201

More on Static Methods and Data

14

• Static data fields are controlled by the class, not the object.

• Static fields will be the same for all instances of a class at any point during runtime

Page 15: Lecture 14: Introduction to Classes and Objects CS201

More on Static Methods and Data

15

public class Borg{private String name;private static int borgCount;

public Borg(String nameIn){name = nameIn;borgCount += 1;

}

public void stateName(){System.out.println(name + " of " + borgCount);

}

public static void main(String[] args){int max = 9;borgCount = 0;Borg[] borgs = new Borg[max];

for(int counter = 0; counter < max; counter++){String name = String.valueOf(counter);borgs[counter] = new Borg(name);

}

for(int counter = 0; counter < max; counter++){borgs[counter].stateName();

}}

}

Page 16: Lecture 14: Introduction to Classes and Objects CS201

toString()

16

• Every class has a built in method called toString()• If you call a print method on a class

without further specification, you will see the return value of toString()• The default method is often not very

useful

Page 17: Lecture 14: Introduction to Classes and Objects CS201

Default toString()

17

public class Clone{private String name;

public Clone(String nameIn){name = nameIn;

}

public static void main(String[] args){

Clone bob = new Clone("Bob");Clone joe = new Clone("Joe");Clone mary = new Clone("Mary");

System.out.println(bob);System.out.println(joe);System.out.println(mary);

}

}

Page 18: Lecture 14: Introduction to Classes and Objects CS201

Custom toString()

18

• You can write your own toString() methods to provide more useful information:

public class Clone{private String name;

public Clone(String nameIn){name = nameIn;

}

public static void main(String[] args){

Clone bob = new Clone("Bob");Clone joe = new Clone("Joe");Clone mary = new Clone("Mary");

System.out.println(bob);System.out.println(joe);System.out.println(mary);

}

public String toString(){return name + " is here!";

}}

Page 19: Lecture 14: Introduction to Classes and Objects CS201

Multi-Class Apps

19

• Real Object-oriented apps usually combine many classes• Classes can be related in various

ways

Page 20: Lecture 14: Introduction to Classes and Objects CS201

Multi-Class Apps

20

• Composition = a relationship in which an object or class contains other objects or classes• This is often explained as a “Has A”

relationship• You have already seen this in the

case of classes that contain Strings• A Family class might contain

references to instances of the Child class

Page 21: Lecture 14: Introduction to Classes and Objects CS201

Multi-Class Apps

21

public class Child{private String name;

public Child(String nameIn){name = nameIn;

}

public void doTask(int taskNum){switch(taskNum){

case 0:playLoudMusic();break;

case 1:crashCar();break;

case 2:makeMomGrouchy();break;

}}

public void playLoudMusic(){System.out.println(name + "'s stereo goes boom bam thump bubaa");

}

public void crashCar(){System.out.println(name + " wrecked the car");

}

public void makeMomGrouchy(){System.out.println("Mom had a fight with " + name + ". Now she has a headache");

}

public String toString(){return name;

}}

Page 22: Lecture 14: Introduction to Classes and Objects CS201

Multi-Class Apps

22

public class Family{private String name;private Child[] kids;

public Family(String nameIn, String[] kidsNames){name = nameIn;kids = new Child[kidsNames.length];for(int counter = 0; counter < kidsNames.length; counter++)

kids[counter] = new Child(kidsNames[counter]);}

public static void main(String[] args){String[] kidsNames = {"Sue", "Bill", "Carla", "Dan"};Family family = new Family("the Smiths", kidsNames);family.live(365);

}

public void live(int days){int taskNum = 0;for(int counter = 0; counter < days; counter++){

System.out.println("\nDay " + counter);int childNum = counter % kids.length;kids[childNum].doTask(taskNum%3);taskNum++;

}

}public String toString(){

return "Welcome to the " + name + "' house";}

}

Page 23: Lecture 14: Introduction to Classes and Objects CS201

Multi-Class Apps

23

• Note that, when you compile the first class in an app from the command line, it will compile all classes it can find in a chain of references• If class a refers to class b, but b does

not have a reference to a, it is easier for you to compile a first.

Page 24: Lecture 14: Introduction to Classes and Objects CS201

Private and Public

24

• The private and public keywords are called visibility modifiers• Public data may be accessed directly by any object that has a

reference to the current object– This means that any other object can change your data in any way that

seems appropriate to whoever wrote it• This leads to unpredictable behavior, because programmers are almost as crazy as

users

• In OOP, data is hardly ever public. Instead we use private or protected data and manipulate it with public methods. This lets the author of the class control what can be done to the class data

• This is the first form you have encountered of encapsulation, which is a key concept in OOP

Page 25: Lecture 14: Introduction to Classes and Objects CS201

Private and Public

25

• Control the ways your data can be accessed or changed by using public methods.public class TeamScore {

private int score = 0;public void fieldGoal(){

score += 3; }

public void touchdown(){score += 6;

}

public void extraPoint(){score += 1;

}

public void safety(){score += 2;

}

public int getScore(){return score;

}

public String toString(){return Integer.valueOf(score).toString();

}}

• Score is private, but we can change it with public methods.• We can control the possible changes because they can only be executed using methods we wrote, not by any logic in any other class.

Page 26: Lecture 14: Introduction to Classes and Objects CS201

Private and Public

26

• Private methods and data may be used only by the object itself

public class VanGogh{private void chop(){

Ears -= 1;}

}

Page 27: Lecture 14: Introduction to Classes and Objects CS201

Packages

27

• Java classes are often organized into packages

Page 28: Lecture 14: Introduction to Classes and Objects CS201

Packages

28

• Java classes are often organized into packages

Page 29: Lecture 14: Introduction to Classes and Objects CS201

Package Private

29

• The default visibility is package private• Package private data and methods are visible to

any object of a class defined in the package

Page 30: Lecture 14: Introduction to Classes and Objects CS201

Getters and Setters

30

• Getters and Setters provide public access to private variables• Setters are also called mutators by fancy people• It is conventional in Java to use private data even if you are going to provide full

access through public getters and setters• Getter method names start with get and use camel case, eg getScore(), even though

the variable names themselves are conventionally not capitalized

Page 31: Lecture 14: Introduction to Classes and Objects CS201

Getters and Setters

31

• The keyword this is a reference to the current object. It has many uses; the first one is in setters when the parameter is given the same name as the field in the class. You need to understand this usage, but if you find it confusing, jJust use a different name for the parameter in the method signature.

private String lastName;private int heightInCm;public String getLastName(){

return lastName;}

public void setHeightInCm(int heightInCmIn){if(heightInCmIn <= 229 && heightInCmIn > 45) heightInCm =

heightInCmIn;Else….}

Page 32: Lecture 14: Introduction to Classes and Objects CS201

Reference

32

•You have already seen how objects are passed to methods; by passing a reference variable•If data changes in an object, you will see the changes from anywhere where you have a reference to the object

Page 33: Lecture 14: Introduction to Classes and Objects CS201

Reference

33

public class Child{private String name;public StringBuilder permanentRecord;

public Child(String nameIn){name = nameIn;permanentRecord = new StringBuilder();

}

public void doTask(int taskNum){switch(taskNum){

case 0:playLoudMusic();break;

case 1:crashCar();break;

case 2:makeMomGrouchy();break;

}}

public void playLoudMusic(){System.out.println(name + "'s stereo goes boom bam thump bubaa");

}

public void crashCar(){System.out.println(name + " wrecked the car");

}

public void makeMomGrouchy(){System.out.println(name + " gave Mom a headache.");

}

public String toString(){return name;

}

public void putDownInPermanentRecord(String offense){permanentRecord.append("\n" + offense);

}

public String getPermanentRecord(){return permanentRecord.toString();

}

public String getName(){return name;}}

Page 34: Lecture 14: Introduction to Classes and Objects CS201

Reference

34

public class Family{private String name;private Child[] kids;

public Family(String nameIn, String[] kidsNames){name = nameIn;kids = new Child[kidsNames.length];for(int counter = 0; counter < kidsNames.length; counter++)

kids[counter] = new Child(kidsNames[counter]);

}

public void callSchool(){AssistantPrincipal norm = new AssistantPrincipal(kids);readPermanentRecords();

}

public String toString(){return "Welcome to the " + name + "s' house";

}

public void readPermanentRecords(){System.out.println("================= Permanent Records ====================");

for(Child child: kids) System.out.println(child.getName() + "'s permanent Record: " + child.getPermanentRecord());}

public static void main(String[] args){String[] kidsNames = {"Sue", "Bill", "Carla", "Dan"};Family family = new Family("the Smiths", kidsNames);family.callSchool();

}

}

Page 35: Lecture 14: Introduction to Classes and Objects CS201

Reference

35

public class AssistantPrincipal{

public AssistantPrincipal(Child[] school){

if(school.length > 0)school[0].putDownInPermanentRecord (“runs with bad crowd");

if(school.length > 1)school[1].putDownInPermanentRecord("aggravated malice");

if(school.length > 2)school[2].putDownInPermanentRecord("gambling during class");

if(school.length > 3)school[3].putDownInPermanentRecord("general disorderliness");

if(school.length > 3)school[3].putDownInPermanentRecord(“bad attitude)”;

}

public void putDownInPermanentRecord(Child child, String offense){child.putDownInPermanentRecord(offense);

}

}

Page 36: Lecture 14: Introduction to Classes and Objects CS201

Definition: State

36

• State is the configuration of data at one point in time

• An object’s state is the set of values of its data fields at one instant