0% found this document useful (0 votes)
15 views57 pages

Lecture 2, 3 - Chapter 3 - Class Vs Object, Fields, Methods, Constructors, Setter-Getter

Uploaded by

Mubbara Majid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views57 pages

Lecture 2, 3 - Chapter 3 - Class Vs Object, Fields, Methods, Constructors, Setter-Getter

Uploaded by

Mubbara Majid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 57

Java™ How to Program, 9/e

© Copyright 1992-2012 by Pearson Education, Inc. All


Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Starter

Write down attributes and actions for a real-world


object (e.g., a mobile phone).

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Attributes  Operations
 Brand  Call
 Model  Send Message
 Color  Connect/Disconnect
 Camera Resolution Internet
(Front/Back)  Lock/Unlock
 Size  Scroll up/down
 Battery capacity  Scan Fingerprint
 Signal Strength  Volume Up/Down
 …  Flash on/off
 Take Image
 Shoot Video
 ...
 Covered in this chapter
 Classes
 Fields
 Methods
 Creating and using Objects
 Setter/getter methods
 UML Class Diagram
 Constructor
 double primitive type

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Create a new class (GradeBook)
 Use it to create an object.
 Each class declaration that begins with keyword

public must be stored in a file that has the same


name as the class and ends with the .java file-name
extension.
 Keyword public is an access modifier.
 Indicates that the class is “available to the public”

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 The main method is called automatically by the Java
Virtual Machine (JVM) when you execute an application.

 A public is “available to the public”


 It can be called from methods of other classes.
 The return type specifies the type of data the method returns
after performing its task.
 Method name follows the return type.
 By convention, method names begin with a lowercase first
letter and subsequent words in the name begin with a capital
letter.
 Empty parentheses after the method name indicate that the
method does not require additional information to perform
its task.
 Together, everything in the first line of the method is
typically called the Method header
 Every method’s body is delimited by left and right braces.
 The method body contains one or more statements that
perform the method’s task.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Use class GradeBook in an application.
 Class GradeBook is not an application because it does not
contain main.
 Can’t execute GradeBook; will receive an error message
like:
 Exception in thread "main"
java.lang.NoSuchMethodError: main
 Must either declare a separate class that contains a main
method or place a main method in class GradeBook.
 To help you prepare for the larger programs, use a separate
class containing method main to test each new class.
 Some programmers refer to such a class as a driver class.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Declare a variable of the class type.
 Each new class you create becomes a new type that can be
used to declare variables and create objects.
 You can declare new class types as needed; this is one reason
why Java is known as an extensible language.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Class instance creation expression
 Keyword new creates a new object of the class specified to the right
of the keyword.
 Used to initialize a variable of a class type.
 The parentheses to the right of the class name are required.
 Parentheses in combination with a class name represent a call to a
constructor, which is similar to a method but is used only at the time
an object is created to initialize the object’s data.
 A static method (such as main) is special
 It can be called without first creating an object of the class in which
the method is declared.
 Typically, you cannot call a method that belongs to another
class until you create an object of that class.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Call a method via the class-type variable
 Variable name followed by a dot separator (.), the method
name and parentheses.
 Call causes the method to perform its task.
 Any class can contain a main method.
 The JVM invokes the main method only in the class used to
execute the application.
 If multiple classes that contain main, then only that main method
is executed in only that class, which is provided along the java
command

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Compiling an Application with Multiple Classes
 Compile the classes in Fig. 3.1 and Fig. 3.2 before executing.
 Type the command
javac GradeBook.java GradeBookTest.java
 Then, Type the command
java GradeBookTest

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Figure 3.3: UML class diagram for class GradeBook.
 Each class is modeled in a class diagram as a rectangle with
three compartments.
 Top: contains the class name centered horizontally in boldface type.
 Middle: contains the class’s attributes, which correspond to instance
variables (Section 3.5).
 Bottom: contains the class’s operations, which correspond to
methods.
 Operations are modeled by listing the operation name
preceded by an access modifier (in this case +) and
followed by a set of parentheses.
 The plus sign (+) corresponds to the keyword public.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 A method can require one or more parameters that
represent additional information it needs to perform its
task.
 Defined in a comma-separated parameter list
 Located in the parentheses that follow the method name
 Each parameter must specify a type and an identifier.
 A method call supplies values—called arguments—for
each of the method’s parameters.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Scanner method nextLine
 Reads characters typed by the user until the newline character is
encountered
 Pressing Enter inserts a newline character at the end of the characters
the user typed.
 Returns a String containing the characters up to, but not
including, the newline
 Scanner method next
 Reads individual words
 Reads characters until a white-space character is encountered, then
returns a String (the white-space character is discarded).
 Information after the first white-space character can be read by other
statements that call the Scanner’s methods later in the program.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 More on Arguments and Parameters
 The number of arguments in a method call must match the
number of parameters in the parameter list of the method’s
declaration.
 The argument types in the method call must be “consistent
with” the types of the corresponding parameters in the
method’s declaration.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 The UML class diagram of Fig. 3.6 models class
GradeBook of Fig. 3.4.
 The UML models a parameter by listing the parameter

name, followed by a colon and the parameter type in


the parentheses- following the operation name.
 The UML type String corresponds to the Java type

String.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Notes on import Declarations
 Classes System and String are in package java.lang
 Implicitly imported into every Java program
 Can use the java.lang classes without explicitly importing them
 Most classes you’ll use in Java programs must be imported explicitly.
 Classes that are compiled in the same directory on disk are in the
same package—known as the default package.
 Classes in the same package are implicitly imported into the source-
code files of other classes in the same package.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 You can create a couple of classes Calculator
and CalculatorTest in the same way as
GradeBook and GradeBookTest.
 Create methods of your choice in the Calculator
class and test them in the CalculatorTest class. Feel
free and get creative in the choice of methods you
want to include in Calculator class.
 Compile Calculator and CalculatorTest classes
and run the CalculatorTest multiple times
after changing the code in CalculatorTest (Be
creative in what to do in CalculatorTest’s
main method).

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Local variables
 Variables declared in the body of a particular method.
 When a method terminates, the values of its local variables are
lost.
 On the other hand, an object has attributes that are
carried with the object as it’s used in a program. Such
attributes exist before a method is called on an object
and after the method completes execution.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 A class normally consists of one or more methods that
manipulate the attributes that belong to a particular
object of the class.
 Attributes are represented as variables in a class declaration.
 Called fields.
 Declared inside a class declaration but outside the bodies of the
class’s method declarations.
 When objects of a class are created, each object has its own
copy of fields (now called instance variables)

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Instance variables typically declared private.
 private is an access modifier.
 private variables and methods are accessible only to methods of
the class in which they are declared.
 Declaring instance private is known as data hiding or
information hiding.
 private variables are encapsulated (hidden) in the object
and can be accessed only by methods of the object’s class.
 Prevents instance variables from being modified accidentally by a
class in another part of the program.
 Set and get methods used to access instance variables.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 When a method that specifies a return type other than void
completes its task, the method returns a result to its calling
method.
 Method setCourseName and getCourseName each
use variable courseName even though it was not declared
in any of the methods.
 Can use an instance variable of the class in each of the classes
methods.

 One method of a class can call another method of the same


class by using just the method name.
 On the contrary, other classes need to create an object of the class
whose method is to be called

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Unlike local variables, which are not automatically
initialized, every field has a default initial value—a
value provided by Java when you do not specify the
field’s initial value.
 Fields are not required to be explicitly initialized before

they are used in a program—unless they must be


initialized to values other than their default values.
 The default value for a field of type String is null

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 set and get methods
 A class’s private fields can be manipulated only by the
class’s methods.
 A client of an object calls the class’s public methods to
manipulate the private fields of an object of the class.
 Classes often provide public methods to allow clients to set
(i.e., assign values to) or get (i.e., obtain the values of)
private instance variables. These methods are termed as
setter and getter methods respectively
 The names of these methods need not begin with set or get, but
this naming convention is recommended.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Figure 3.9 contains an updated UML class diagram for
the version of class GradeBook in Fig. 3.7.
 Models instance variable courseName as an attribute in the
middle compartment of the class.
 The UML represents instance variables as attributes by listing
the attribute name, followed by a colon and the attribute type.
 A minus sign (–) access modifier corresponds to access
modifier private.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
public class MobilePhone {

private int batteryPercentage; // Setter for batteryPercentage


private int signalStrength; public void chargePhone(int chargeAmount) {
// This setter method ensures battery doesn't
// Constructor exceed 100% or fall below 0%
public MobilePhone(int battery, int signal) { this.batteryPercentage = Math.min(100,
this.batteryPercentage = battery; this.batteryPercentage + chargeAmount);
this.signalStrength = signal; this.batteryPercentage = Math.max(0,
} this.batteryPercentage);
}
// Public methods
public void makeCall() { // Getter for signalStrength
System.out.println("Calling..."); public int getSignalStrength() {
// ... other logic return signalStrength;
} }

public void sendMessage() { // ... Other methods, getters, and setters


System.out.println("Sending message...");
// ... other logic }
}

// Getter for batteryPercentage


public int getBatteryPercentage() {
return batteryPercentage;
}

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 When an object of a class is created, its instance
variables are initialized by default.
 Each class can provide a constructor that initializes an

object of a class when the object is created.


 Java requires a constructor call for every object that is

created.
 Keyword new requests memory from the system to

store an object, then calls the corresponding class’s


constructor to initialize the object.
 A constructor MUST have the same name as the class.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 By default, the compiler provides a default constructor in a
class that does not explicitly include a constructor.
 Instance variables are initialized to their default values, e.g. integer
type instance variables are assigned 0
 Can provide your own constructor to specify custom
initialization for objects of your class.
 Like any method, a constructor can contain parameters,
which can be used inside constructor to initialize instance
variables.
 Constructors cannot return values, so they cannot specify a
return type.
 Normally, constructors are declared public.
 If you explicitly declare a constructor for a class, the Java
compiler will not create a default constructor for that class.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 The UML class diagram of Fig. 3.12 models class
GradeBook of Fig. 3.10, which has a constructor that
has a name parameter of type String.
 Like methods, the UML models constructors in the

third compartment of a class in a class diagram.


 To distinguish a constructor, the UML requires that the

word “constructor” be placed between « and » before


the constructor’s name.
 List constructors before other operations in the third

compartment.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 In Java, Types are divided into primitive types and
reference types.
 The primitive types are boolean, byte, char, short,
int, long, float and double.
 A primitive-type variable can store exactly one value of its
declared type at a time.
 Primitive-type Instance variables are initialized by default—
variables of types byte, char, short, int, long,
float and double are initialized to 0, and variables of
type boolean are initialized to false.
 Primitive-type Local variables are NOT initialized by
default

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 All non-primitive types (e.g. the class types) are reference
types.
 Programs use variables of reference types (normally called
references) to store the locations of objects in the
computer’s memory.
 The new keyword creates the object in memory
 Such a variable is said to refer to an object in the program.
 Contrary to primitive types, objects that are referenced may
each contain many instance variables and methods.
 Reference-type instance variables are initialized by default
to the value null
 A reserved word that represents a “reference to nothing.”

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
Example – illustration of Primitive Types
vs. Reference Types
 Consider the Class SpeciesFourthTry given below & Refer to Lecture Notes on
Reference Type Variables [From Walter Savitch Book].
package Lecture4;
public class SpeciesFourthTry {
public String name;
public int population;
public double growthRate;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getPopulation() {


return population;
}

public void setPopulation(int population) {


this.population = population;
}

public double getGrowthRate() {


return growthRate;
© Copyright 1992-2012 by Pearson
} Education, Inc. All Rights Reserved.
Example – illustration of Primitive Types
vs. Reference Types

public void setGrowthRate(double growthRate) {


this.growthRate = growthRate;
}

public void setSpecies(String newName, int newPopulation,


double newGrowthRate)
{
name = newName;
if (newPopulation >= 0)
population = newPopulation;
else
{
System.out.println(
"ERROR: using a negative population.");
System.exit(0);
}
growthRate = newGrowthRate;
}

public void writeOutput()


{
System.out.println("Name = " + name);
System.out.println("Population = " + population);
System.out.println("Growth rate = " + growthRate + "%");
}
} © Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.

You might also like