Lect07-ClassAndObject

Download Report

Transcript Lect07-ClassAndObject

Class and Object
Lecture 7
1
Classes
Classes are constructs that define objects of the
same type.
A Java class uses instance variables to define
data fields/attributes and methods to define
behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct objects from the class.
2
Class
Object
 A blueprint for objects
of a particular type
 Defines the structure
(number, types) of the
attributes
 Defines available
behaviors of its objects
Attributes
Behaviors
3
Class: Car
Object: a car
Attributes:
String model
Color color
int numPassengers
double amountOfGas
Attributes:
model = "Mustang"
color = Color.YELLOW
numPassengers = 0
amountOfGas = 16.5
Behaviors:
Behaviors:
Add/remove a passenger
Get the tank filled
Report when out of gas
4
Color Constants
 There are predefined constants that you can use for
colors.
Color.BLACK
Color.CYAN
Color.GRAY
Color.LIGHT_GRAY
Color.ORANGE
Color.RED
Color.YELLOW
Color.BLUE
Color.DARK_GRAY
Color.GREEN
Color.MAGENTA
Color.PINK
Color.WHITE
5
Classes and Source Files
 Each class is stored in a separate file
 The name of the file must be the same as the
name of the class, with the extension .java
Car.java
public class Car
{
...
}
By convention, the
name of a class
(and its source file)
always starts with
a capital letter.
(In Java, all names are case-sensitive.)
6
SomeClass.java
import ...
import statements
public class SomeClass
{
 Fields
 Constructors
 Methods
}
Class header
Attributes / variables that define the
object’s state; can hold numbers,
characters, strings, other objects
Procedures for constructing
a new object of this class
and initializing its fields
Actions that an object
of this class can take
(behaviors)
7
Class Definition
public class Circle {
Circle
- radius: double
- area: double
+ findArea(): double
private double radius, area;
final double PI = 3.14159;
Circle (double r) {
radius=r;
}
public double findArea() {
area= radius*radius*PI;
UML class diagram
return area;
}
}
8
Data Fields
 A.k.a. instance variables
 Constitute “private memory” of an object
 Each field has a data type (int, double, String,
Image, Foot, etc.)
 Each field has a name given by the
programmer
9
You name it!
Fields (cont’d)
private [static] [final] datatype name;
Usually
private
May be present:
means the field is
shared by all
objects in the class
primitive: int, double,
etc., or an object:
String, Image, Foot
May be present:
means the field
is a constant
private Foot leftFoot;
10
Constructors
 A constructor is a a special kind of methods for
creating objects of the class.
 Constructors do not have a return type (not
even void) and they do not return a value.
 All constructors in a class must have the same
name — the name of the class.
 Constructors may take parameters.
 Constructors are invoked using the new
operator when an object is created.
Constructors play the role of initializing objects.
11
Creating Objects Using
Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
12
Default Constructor
•A class may be declared without constructors.
•In this case, a no-arg constructor that takes no
parameters, with an empty body is implicitly declared in
the class.
•This constructor, called a default constructor, is provided
automatically only if no constructors are explicitly declared
in the class.
•In other words: If a programmer does not define any
constructors, Java provides one default no-args
constructor, which allocates memory and sets fields to the
default values.
13
Constructors (cont’d)
 If a class has more than one constructor, they
must have different numbers and/or types of
parameters.
 This is called constructor overloading.
14
Constructors (cont’d)
public class Fraction
{
private int num, denom;
public Fraction (int n, int d)
{
num = n;
denom = d;
reduce ();
}
public Fraction ( )
{
num = 0;
“No-args”
denom = 1;
constructor
}
public Fraction (int n)
{
num = n;
denom = 1;
}
Continued 
public Fraction (Fraction other)
{
num = other.num;
denom = other.denom;
}
...
Copy
}
constructor
15
Constructors (cont’d)
 A nasty bug:
public class MyWindow
extends JFrame
{
...
// Constructor:
public void MyWindow ( )
{
...
}
...
Compiles fine, but
the compiler thinks
this is a method and
uses MyWindow’s
default no-args
constructor instead.
16
Constructors (cont’d)
 Constructors of a class can call each other using
the keyword this — a good way to avoid
duplicating code:
public class Fraction
{
...
public Fraction (int n)
{
this (n, 1);
}
...
...
public Fraction (int p, int q)
{
num = p;
denom = q;
reduce ();
}
...
17
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
To declare a reference variable, use the syntax:
ClassName objectRefVar;
Example:
Circle myCircle;
18
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
Assign object reference
Create an object
Example:
Circle myCircle = new Circle();
19
Accessing Objects
 Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
 Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., myCircle.getArea()
20
Example: Declare an object
2 steps are Involved :
1.
Declaring Object Reference Variable named
circle1
Circle circle1;
2.
Creating Objects
circle1 = new Circle(2.3);
Can combine;
Circle circle1 = new Circle(2.3);
21
public class Circle {
private double radius, area;
final PI = 3.14159;
File Name?
Save as “______.java”
Circle (double r) {
radius = r;
}
public double findArea() {
area= radius*radius*PI;
return area;
}
}
public class TestCircle {
public static void main(String[] args) {
Circle circle1 = new Circle(2.3);
System.out.println("The area of the circle of radius "+ circle1.radius + " is " +
circle1.findArea());
}
}
22