Date post: | 04-Jan-2016 |
Category: |
Documents |
Upload: | rodger-johnson |
View: | 221 times |
Download: | 0 times |
Classes, Objects, and Methods
Overview
What are classes, objects, and methods?
Using objects and methods Declaring classes and methods Information hiding and encapsulation Objects and references Review
What are classes, objects, and methods
What are objects and classes?
Objects can represent any particular object in the real world. Books, houses, automobiles, people, foods, etc. Sometimes called “instantiations” or “instances”.
A class is a definition of a kind of object, like you could have a Book class that you define what kinds of objects books will be. It is like a blueprint.
What makes objects different from variables?
Objects, like variables, have places to store data.
Objects, unlike variables, have methods or actions that can be performed on those objects. We will see examples later.
Class example: Book
Data:– name of book:– author:– is it checked out:– who its checked out by:
Methods:– checkOut:– checkIn:
Objects(instantiations) of Book:
name: The Hobbittauthor: J.R.R. Tolkienis It Checked Out: Yeschecked Out By: Fred Stevens
name: Dark Optimismauthor: Alex Steinis It Checked Out: Yeschecked Out By: Eric Davis
name: War and Peaceauthor: Leo Tolstoyis It Checked Out: Nochecked Out By: null
Object name: book1
Object name: ericsFav
Object name: boringBook
Like variable names.Identifies the particularobject.
Like the value or datastored inside of a variable.
Class definition of Automobile
Data– amount of fuel:– speed:– license plate:
Methods(actions):– increaseSpeed:– stop:
Instantiations(objects) of Automobile:
fuel: 10 gallonsspeed: 15 mphlicense: 1XV54
fuel: 2 gallonsspeed: 0 mphlicense: 142FG
fuel: 12 gallonsspeed: 45 mphlicense: RVG224
fuel: 5 gallonsspeed: 65 mphlicense: SMOOD
Object name: car1
Object name: forSaleObject name: ericsCar
Object name: car2
What are methods?
Methods are the actions that we call on the object to do (invoke).
We tell a book to check itself out(by scanning it).
We ask an automobile to accelerate(by pushing the gas).
Method examples
ericsCar.accelerate();
book1.checkIn();
Ask ericsCar to accelerate. Only applies tothis one object. None of the other cars accelerate.
Object Method
Using objects and methods
Using objects and methods
We have already been using objects and methods(possibly without realizing it).
String is a class. .equals() is a method SavitchIn is a class. All of the
readLine(), readLineInt(), readLineNonwhiteChar(), etc. are methods.
Declaring objects
We declare objects of a class the same way that we declare variables of a type(we initialize them differently, though):
<ClassName> <variableName>;
String userInput;Book book1, book2, boringBook;Automobile ericsCar, suesCar;
Initializing objects
Just as we would initialize variables to some default value(such as 0, or whatever), we also want to be able to initialize objects to a default value.
Since objects can have lots of different types in them, we can’t just set the object to a simple data value (such as 0). Instead we use the new operator.
Initializing objects
<objectName> = new <ClassName>();
or
<ClassName> <objectName> = new <ClassName>();
userInput = new String(); //empty stringbook1 = new Book(); //default bookAutomobile newCar = new Automobile();Automobile usedCar = new Automobile();
Calling methods of an object Once we have an object initialized to
something, we can start calling methods on that particular object(often called “invoking”). Usually need an object to call a method of the class:<objectName>.<methodName>(<parameters>);
string1.equals(string2);book1.checkIn();ericsCar.stop(); Sometimes the methods need
some extra information. This infois taken in through the use of “parameters.”
Calling object
What about SavitchIn? We never declare objects there and we use methods... Some classes have special methods
(called static methods) that allow you to use the methods without requiring you to have an object.
SavitchIn has static methods, as well as the Math class. So we can use the methods in these classes without declaring Math objects or SavitchIn objects.
Declaring classes and methods
Creating classes Every class that is usable by another
program is called a “public” class. We can have only one public class per file,
and the class name must match the filename(just like we have always been doing).
As long as we keep the classes in the same directory, we should not have any problems with using other classes.
Declaring classes- general form
public class <ClassName>{
<instance variable declarations>;...
<method declarations and definitions>;}
Like author or title in the Book class, or speedor gallons in the Automobile class.
Like checkIn or checkOut in Book, or accelerateor stop in Automobile.
A first class- The Book example.
The code in the following Book class (along with the BookTest class) can be found at
www.cs.uaf.edu/~cs103/Handouts/Book.java
www.cs.uaf.edu/~cs103/Handouts/BookTest.java
Book example instance variable declaration. public class Book{
public String author;public String name;public boolean isCheckedOut;public String checkedOutByWho;...
<method declarations and definitions>;}
Means that others outsideof the class have access to read/write to this variable.We’ll change this soon.
Variables usually aren’t initializedhere. They are usually initialized ina method or outside the class
Class methods, declaration/definition Declaration of methods is giving the
header of the method, that is telling whether the method is public, what it accepts as arguments or parameters, and what it returns. (interface)
Definition of methods is the actual code that does the work for the method. (implementation)
Book example, methods
...public void checkOut(){
System.out.print("Enter the name of the person” +“ that wants to check " +bookName + " out:");checkedOutBy = SavitchIn.readLine();isCheckedOut = true;
}...
Usable by anyone
Doesn’t return anything, just does something.
Whole line is the methoddeclaration. (interface)
This whole section(often called the “body”) is the definition of the method, the code that actually does stuff.(implementation)
Book examples, methods...public void checkOut(){
System.out.print("Enter the name of the person” +“ that wants to check " +bookName + " out:");checkedOutBy = SavitchIn.readLine();isCheckedOut = true;
}...
Imagine that this method was called using book1 as the calling object(book1.checkOut()). Then the variables in this method would bebook1’s version of the variables. So the variables in this method wouldbe the same as ...
book1.checkedOutBy = SavitchIn.readLine();book1.isCheckedOut = true;
}...
The this parameter. As we saw in the last slide, the instance variables
used in a method refer to the particular calling object’s variables (thus isCheckedOut referred to book1.isCheckedOut).
Sometimes we write this.isCheckedOut to explicitly refer to the calling object (in this case it means the computer replaces the word “this” with “book1.”)
Not used horribly often, but sometimes necessary.
Methods that take + return values
Unlike our Book example, not all methods take no information(no parameters) or return no information(void methods).
Methods that require information be passed to them have a parameter list.
Methods that return information have non-void types.
Methods that take+return values:Triangle Example.
...public void setBase(double baseIn){
if(baseIn > 0)base = baseIn;
else{
System.out.println("Incorrect “ + base size. Must be positive.");
System.exit(0);}
}...
Parameter list requiresthat a double be passedto this method when itis called.
Returns nothing
Methods the take+return values:Triangle Example continues
...public double getHeight(){
return height;}...
By the time this method finishesit will return a double value.
Method takes no parameters
Gives the value height to whoever calledthis method.
More on return statements You must always return the same type as is
mentioned in the method declaration. If it says it is going to return a double, return a double variable.
You may need to cast variables to return them.
return (double)integer1; If you are in a void method, you can still use return
to exit the method, just don’t have any value that is returned.
return;
More on parameters
The above method declaration states that the method requires an int and a double to be passed to it, when called, in that order.
int int1 = 1;
double double1 =2.0; someObject.someMethod(int1,double1);
The types of the variables need to match, but the names do not!
In fact, the variable names are “local” to the method(they are not meaningful outside the method).
public void someMethod(int x, double y)
Local variables.
All declared variables are “local” to the block in which they were declared. This means that they can not be used outside of that block. In Java, we also have the restriction that two variables can not have the same name inside a single method, whether they are in the same block or not.
You can use the same variable name in two different methods, and each variable is completely unrelated to the other.
Local variable examples...//variable i not initialized yet.for(int i = 0; i<10; i++){
System.out.println(i);}System.out.println(i); //won’t work....if(true){
int k = 10;}System.out.println(k); //won’t work...
Local variables and parameters
When we use the above method by calling it someObject.someMethod(4, 5.0);
the computer takes the arguments that we pass in (the 4, and the 5.0) and it replaces the formal arguments (x, y) with the numbers wherever they occur in the method.
public void someMethod(int x, double y)
Local variable examples... //in class SomeClasspublic void method1(int x){ double y = 0.0; System.out.println(y + “ , “ + x);}
public void method2(int x){ double y = 10.0; System.out.println(y + “, “ + x);}...//in another file using SomeClassSomeClass x, y;x.method1(1);x.method2(1);y.method1(5);y.method2(5);
Local variable examples... //in class SomeClasspublic void method1(int x){ double y = 0.0; System.out.println(y + “ , “ + x);}
public void method2(int x){ double y = 10.0; System.out.println(y + “, “ + x);}...//in another file using SomeClassSomeClass x, y;x.method1(1);x.method2(1);y.method1(5);y.method2(5);
0.0, 110.0, 10.0, 510.0, 5
Parameter/argument rules
You must specify the type before each formal parameter, even if they are all the same typepublic void someMethod(int x, int y, int z);
When calling the method, you must specify the same number of arguments, as the same types, in the same order as is listed in the method declaration. someObject.someMethod(1,2); //won’t work
someObject.someMethod(1, ’c’, 3); //won’t work
someObject.someMethod(1,2,3); //will work.
Declaring classes review
Can we have more than one public class per file? How do we declare instance variables for a
class? How do we declare methods for a class? If a method asks for 5 integers when it is
invoked(5 integer parameters), do we have to supply all 5 when calling it?
Can we access variables declared inside of a loop when we are outside the loop?
Information Hiding and Encapsulation
Information Hiding
Information hiding, sometimes called “abstraction”, is the idea of hiding the details of the implementation (or how something is done) from the user, only giving them the what the method accomplishes.
Information hiding is good. If you write a class with good information hiding,
you can completely change the implementation without the user noticing a thing on their end.
Examples of information hiding
You can drive a car without knowing anything about internal combustion engines, transmissions, or anti-lock brakes.
You can read a watch without knowing about gear ratios, crystals, etc.
Someone could rip out the guts of these objects and replace them with another implementation(a bigger engine, an atomic clock) and you likely would not know the difference.
Our goals as information hiders
Create classes and methods that people can use without knowing the details of our code.
Have classes and methods such that we can later change the implementation to something completely different without the user ever knowing.
Methods of information hiding
Good comments! Private instance variables. Mutator and accessor methods.
Commenting Comment before each class and before each
method in the class. For methods:
– Preconditions: What conditions must be satisfied before using this method. If the conditions are not satisfied, there is not guarantee that the method will work correctly.
– Postconditions: What actions the method performs on the data. What is returned.
If your commenting is good, you can use javadoc on your code to produce documentation.
public vs. private modifiers Up till now, we have used public modifiers for
everything(methods, instance variables, classes). This means anyone can access them.
To follow good information hiding techniques, we should always have only private instance variables (NO public instance variables).
The private modifier makes it so only members of the class can access the private data(or methods). This means other objects of the same class can access private data.
How to get at private data.
If all of the data in the class is private, how can a user get access to the data? Through our methods.
If the user will need to be able to read the data(or you don’t mind them reading it at least), then you can include an accessor method (a get method) for the data.
If the user needs to write to the data, then you can include a mutator method (a set method).
A BetterBookpublic class BetterBook{
private String authorName;private String bookName;
.../************************************** * Get author name *************************************/ public String getAuthorName() {
return authorName; } /******************************************* * set author name *****************************************/ public void setAuthorName(String newAuthorName) {
authorName = newAuthorName; }
...
A BetterBook example
...book2.setAuthorName("Alex Stein");//the hard way.book2.setBookName("Dark Optimism");...
Encapsulation
Encapsulation is a form of information hiding. The idea is to split the class definition into two
parts: user interface and the implementation. We have already been talking about good ways
to do encapsulation. Though you need the implementation to run a
program that uses a class, you should not need to know anything about the implementation to write code that uses the class.
Encapsulation review- ways to have good encapsulation Good Comments! Before each class and
method. Private instance variables (and any helper
functions the user doesn’t need, but you like). Mutator and accessor methods(if necessary).
Did I do encapsulation well?
Does the user require knowledge of your implementation to use your class?
Can you make a program using your class, change the implementation of the class, and still have your other program run correctly? If so, then you have created good encapsulation/information hiding for your class.
Review- Encapsulation and Information Hiding What is information hiding? What keyword do we use to hide our
information? How do we allow others access to our hidden
information? What kinds of instance variables should we
never have anymore? What should we have at the beginning of every
class and method?
Objects and References- The nitty gritty of Objects.
Objects- what are they really?
When we declare an object in our program, the variable name that we use for it doesn’t really refer to the whole object, it only refers to the memory address that contains the information in our object.
Thus assignment(=) and equality(==) statements between objects are looking at only the memory addresses of the objects, not the actual data inside the object.
Objects and primitive storage
int i = 0;BetterBook book1 =
new BetterBook();
i 0
book1 2054
BetterBook book2 =new BetterBook();
book2 1036
1036
2054
????????
Objects and primitive storage
int i = 0;BetterBook book1 =
new BetterBook();
i 0
book1 2054
BetterBook book2 =new BetterBook();
book1.setAuthorName(“Roald”);
book1.setBookName(“Some”);
book2.setAuthorName(“Stein”);
book2.setBookName(“Short”);
book2 1036
1036
2054
SteinShort??RoaldSome??
Objects and primitive storage
int i = 0;BetterBook book1 =
new BetterBook();
i 0
book1 1036
BetterBook book2 =new BetterBook();
book1.setAuthorName(“Roald”);
book1.setBookName(“Some”);
book2.setAuthorName(“Stein”);
book2.setBookName(“Short”);
book1=book2;
book2 1036
1036
2054
SteinShort??RoaldSome??
Garbage. Not accessible.
Moral of the story:
Don’t use = or == when using classes. It won’t work like you expect.
So we need ways of assigning the value of one object to another and of comparing two objects.
We do these operations by defining an equals() method in every class and by defining a clone() method.
Defining an equals()
For class SomeClass we would define an equals as follows:
public boolean equals(SomeClass otherObject){
//compares all the data to see if it // is true.
}
Triangle examplepublic boolean equals(Triangle otherTri){
if((this.base == otherTri.base) && (this.height == otherTri.height)) return true;else
return false;}
…Triangle tri1 = new Triangle(),
tri1 = new Triangle();tri1.setBase(1); tri2.setBase(1);tri1.setHeight(2); tri2.setHeight(3);if(tri1.equals(tri2))
System.out.println(“They are equal”);else
System.out.println(“They are different”);
tri1
tri2
The difference between Class parameters and primitive parameters. Primitive values are passed “by value”
so you are not allowed to make any changes to the parameter value that will last outside the method.
Class parameters are passed “by reference” so you can make changes to the data in the object and it will still be changed after the method is over.
Triangle example.
public void makeEqual(Triangle otherTri){
otherTri.base = this.base;otherTri.height = height;
}
public void tryMakeEqual(int inbase, int inheight){
inbase = this.base;inheight = this.height;
}
...
tri1.tryMakeEqual(tri2.getBase(), tri2.getheight());tri1.makeEqual(tri2);
Does nothing to tri2
Sets tri2 equal to tri1;
Class details review
What does the object name really store in memory?
How do we compare two objects? What is the difference between Class
parameters and primitive parameters?
Review
Review questions to ask yourself
What are classes? What are objects? What are methods?
How are classes and objects related? How many public classes can I have in
a file? What keyword do we use to initialize a
new object of some class?
Review questions to ask yourself
What are instance variables? What keyword should I put before all of
my instance variables? What is the difference between public
and private? Why do we want to encapsulate or hide
our information?
Review questions to ask yourself
What are parameters and arguments? What keyword do you use if your method is
not going to return any data? What keyword do you use if your method is
going to return data? What does the “this” keyword refer to? How many arguments need to be passed to
the following method? What types are they?public void someMethod(int x, double y, char x);
Review questions to ask yourself
What do we call the methods that let us get at private data (2 of them)?
What should we have at the beginning of every class and method?
What does an object name actually store in memory?