360 likes | 510 Views
Lecture 14: Introduction to Classes and Objects. CS201. Abstraction. Some definitions of Abstract (adjective): Considered apart from any application to a particular object; removed from; apart from; separate ; abstracted .
E N D
Abstraction 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
Abstraction • 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?
Abstraction 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
Object Oriented Programming 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
Objects • 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
Account Class 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; } }
Classes • 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();
Static vsNonStatic Methods • 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();
Classes public class Archimedes{ public static void main(String[] args){ Archimedes arch = new Archimedes(); arch.sayHi(); } private void sayHi(){ System.out.println("HI!"); } }
Constructors • 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.
Constructors 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); } }
Why don’t we just use static methods for everything? 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); } }
More on Static Methods and Data 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
More on Static Methods and Data 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(); } } }
toString() 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
Default toString() 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); } }
Custom toString() 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!"; } }
Multi-Class Apps Real Object-oriented apps usually combine many classes Classes can be related in various ways
Multi-Class Apps 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
Multi-Class Apps public class Child{ private String name; public Child(String nameIn){ name = nameIn; } public void doTask(inttaskNum){ 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; } }
Multi-Class Apps 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){ inttaskNum = 0; for(int counter = 0; counter < days; counter++){ System.out.println("\nDay " + counter); intchildNum = counter % kids.length; kids[childNum].doTask(taskNum%3); taskNum++; } } public String toString(){ return "Welcome to the " + name + "' house"; } }
Multi-Class Apps 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.
Private and Public • 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
Private and Public • 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 intgetScore(){ 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.
Private and Public • Private methods and data may be used only by the object itself public class VanGogh{ private void chop(){ Ears -= 1; } }
Packages Java classes are often organized into packages
Packages Java classes are often organized into packages
Package Private The default visibility is package private Package private data and methods are visible to any object of a class defined in the package
Getters and Setters 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
Getters and Setters • 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…. }
Reference 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
Reference 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;} }
Reference 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(); } }
Reference 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); } }
Definition: State • 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