Classes, Objects, and Methods - PowerPoint PPT Presentation

About This Presentation
Title:

Classes, Objects, and Methods

Description:

author: Leo Tolstoy. is It Checked Out: No. checked Out By: null. Object name: book1 ... The types of the variables need to match, but the names do not! ... – PowerPoint PPT presentation

Number of Views:68
Avg rating:3.0/5.0
Slides: 70
Provided by: erics84
Learn more at: https://www.cs.uaf.edu
Category:

less

Transcript and Presenter's Notes

Title: Classes, Objects, and Methods


1
Classes, Objects, and Methods
2
Overview
  • What are classes, objects, and methods?
  • Using objects and methods
  • Declaring classes and methods
  • Information hiding and encapsulation
  • Objects and references
  • Review

3
What are classes, objects, and methods
4
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.

5
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.

6
Class example Book
  • Data
  • name of book
  • author
  • is it checked out
  • who its checked out by
  • Methods
  • checkOut
  • checkIn

7
Objects(instantiations) of Book
Like variable names. Identifies the
particular object.
Object name book1
name The Hobbitt author J.R.R. Tolkien is It
Checked Out Yes checked Out By Fred Stevens
Like the value or data stored inside of a
variable.
Object name ericsFav
name Dark Optimism author Alex Stein is It
Checked Out Yes checked Out By Eric Davis
Object name boringBook
name War and Peace author Leo Tolstoy is It
Checked Out No checked Out By null
8
Class definition of Automobile
  • Data
  • amount of fuel
  • speed
  • license plate
  • Methods(actions)
  • increaseSpeed
  • stop

9
Instantiations(objects) of Automobile
Object name car1
Object name car2
fuel 10 gallons speed 15 mph license 1XV54
fuel 5 gallons speed 65 mph license SMOOD
Object name forSale
Object name ericsCar
fuel 2 gallons speed 0 mph license 142FG
fuel 12 gallons speed 45 mph license RVG224
10
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).

11
Method examples
Object
Method
ericsCar.accelerate()
Ask ericsCar to accelerate. Only applies to this
one object. None of the other cars accelerate.
book1.checkIn()
12
Using objects and methods
13
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.

14
Declaring objects
  • We declare objects of a class the same way that
    we declare variables of a type(we initialize them
    differently, though)

ltClassNamegt ltvariableNamegt String
userInput Book book1, book2, boringBook Automobi
le ericsCar, suesCar
15
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 cant just set the object to a simple
    data value (such as 0). Instead we use the new
    operator.

16
Initializing objects
ltobjectNamegt new ltClassNamegt() or ltClassNamegt
ltobjectNamegt new ltClassNamegt()
userInput new String() //empty string book1
new Book() //default book Automobile newCar
new Automobile() Automobile usedCar new
Automobile()
17
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

ltobjectNamegt.ltmethodNamegt(ltparametersgt) string1.
equals(string2) book1.checkIn() ericsCar.stop()

Sometimes the methods need some extra
information. This info is taken in through the
use of parameters.
Calling object
18
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.

19
Declaring classes and methods
20
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.

21
Declaring classes- general form
public class ltClassNamegt ltinstance variable
declarationsgt ... ltmethod declarations
and definitionsgt
Like author or title in the Book class, or
speed or gallons in the Automobile class.
Like checkIn or checkOut in Book, or
accelerate or stop in Automobile.
22
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

23
Book example instance variable declaration.
Means that others outside of the class have
access to read/write to this variable. Well
change this soon.
public class Book public String
author public String name public boolean
isCheckedOut public String checkedOutByWho ...
ltmethod declarations and definitionsgt
Variables usually arent initialized here. They
are usually initialized in a method or outside
the class
24
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)

25
Book example, methods
Usable by anyone
Doesnt return anything, just does something.
... public void checkOut() System.out.print("En
ter the name of the person that wants to
check " bookName " out") checkedOutBy
SavitchIn.readLine() isCheckedOut true ...
Whole line is the method declaration. (interface)
This whole section(often called the body) is
the definition of the method, the code that
actually does stuff.(implementation)
26
Book examples, methods
... public void checkOut() System.out.print("En
ter 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 be book1s
version of the variables. So the variables in
this method would be the same as
... book1.checkedOutBy SavitchIn.readLine() b
ook1.isCheckedOut true ...
27
The this parameter.
  • As we saw in the last slide, the instance
    variables used in a method refer to the
    particular calling objects 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.

28
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.

29
Methods that takereturn valuesTriangle
Example.
Returns nothing
... public void setBase(double baseIn) if(baseI
n gt 0) base baseIn else System.out.prin
tln("Incorrect base size. Must be
positive.") System.exit(0) ...
Parameter list requires that a double be
passed to this method when it is called.
30
Methods the takereturn valuesTriangle Example
continues
By the time this method finishes it will return a
double value.
... public double getHeight() return
height ...
Method takes no parameters
Gives the value height to whoever called this
method.
31
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 dont have any
    value that is returned.
  • return

32
More on parameters
public void someMethod(int x, double y)
  • 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).

33
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.

34
Local variable examples
...//variable i not initialized yet. for(int i
0 ilt10 i) System.out.println(i) System.o
ut.println(i) //wont work. ... if(true) int
k 10 System.out.println(k) //wont work ...
35
Local variables and parameters
public void someMethod(int x, double y)
  • 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.

36
Local variable examples
... //in class SomeClass public 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
SomeClass SomeClass x, y x.method1(1) x.method2(
1) y.method1(5) y.method2(5)
37
Local variable examples
... //in class SomeClass public 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
SomeClass SomeClass x, y x.method1(1) x.method2(
1) y.method1(5) y.method2(5)
0.0, 1 10.0, 1 0.0, 5 10.0, 5
38
Parameter/argument rules
  • You must specify the type before each formal
    parameter, even if they are all the same type
  • public 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) //wont work
  • someObject.someMethod(1, c, 3) //wont work
  • someObject.someMethod(1,2,3) //will work.

39
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?

40
Information Hiding and Encapsulation
41
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.

42
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.

43
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.

44
Methods of information hiding
  • Good comments!
  • Private instance variables.
  • Mutator and accessor methods.

45
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.

46
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.

47
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 dont 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).

48
A BetterBook
public 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 ...
49
A BetterBook example
... book2.setAuthorName("Alex Stein")//the hard
way. book2.setBookName("Dark Optimism") ...
50
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.

51
Encapsulation review- ways to have good
encapsulation
  • Good Comments! Before each class and method.
  • Private instance variables (and any helper
    functions the user doesnt need, but you like).
  • Mutator and accessor methods(if necessary).

52
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.

53
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?

54
Objects and References- The nitty gritty of
Objects.
55
Objects- what are they really?
  • When we declare an object in our program, the
    variable name that we use for it doesnt 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.

56
Objects and primitive storage
int i 0 BetterBook book1 new BetterBook()
i
0
2054
book1
book2
1036
BetterBook book2 new BetterBook()
1036
? ? ? ?
2054
? ? ? ?
57
Objects and primitive storage
int i 0 BetterBook book1 new BetterBook()
i
0
2054
book1
book2
1036
BetterBook book2 new BetterBook() book1.setAut
horName( Roald) book1.setBookName( Some) b
ook2.setAuthorName( Stein) book2.setBookName(
Short)
1036
Stein Short ? ?
2054
Roald Some ? ?
58
Objects and primitive storage
int i 0 BetterBook book1 new BetterBook()
i
0
1036
book1
book2
1036
BetterBook book2 new BetterBook() book1.setAut
horName( Roald) book1.setBookName( Some) b
ook2.setAuthorName( Stein) book2.setBookName(
Short) book1book2
1036
Stein Short ? ?
2054
Roald Some ? ?
Garbage. Not accessible.
59
Moral of the story
  • Dont use or when using classes. It wont
    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.

60
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.
61
Triangle example
public boolean equals(Triangle otherTri) if((th
is.base otherTri.base) (this.height
otherTri.height)) return true else retur
n false
tri1
tri2
Triangle tri1 new Triangle(), tri1 new
Triangle() tri1.setBase(1) tri2.setBase(1) tri1
.setHeight(2) tri2.setHeight(3) if(tri1.equals(t
ri2)) System.out.println(They are
equal) else System.out.println(They are
different)
62
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.

63
Triangle example.
public void makeEqual(Triangle otherTri) otherT
ri.base this.base otherTri.height
height public void tryMakeEqual(int inbase,
int inheight) inbase this.base inheight
this.height ... tri1.tryMakeEqual(tri2.getBas
e(), tri2.getheight()) tri1.makeEqual(tri2)
Does nothing to tri2
Sets tri2 equal to tri1
64
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?

65
Review
66
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?

67
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?

68
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)
69
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?
Write a Comment
User Comments (0)
About PowerShow.com