0% found this document useful (0 votes)
59 views19 pages

Chapter 2 Classes and Objects Overview

- A Java program consists of classes and objects. A class defines attributes and behaviors, while objects are instances of a class. - Classes are defined in .java files and contain fields to store attribute values and methods to define behaviors. Libraries organize classes into packages. - The import statement allows using classes from libraries without specifying the full package name. Classes contain constructors to initialize new objects.

Uploaded by

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

Chapter 2 Classes and Objects Overview

- A Java program consists of classes and objects. A class defines attributes and behaviors, while objects are instances of a class. - Classes are defined in .java files and contain fields to store attribute values and methods to define behaviors. Libraries organize classes into packages. - The import statement allows using classes from libraries without specifying the full package name. Classes contain constructors to initialize new objects.

Uploaded by

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

M.

El Dick - I2211

Classes and Objects


 A Java program consists of one or more classes
 A class is an abstract description of objects
 Here is an example class:
 class Dog { ...description of a dog goes here... }
 Here are some objects of that class:

CLASSES AND OBJECTS


Chapter 2 M. El Dick - I2211

More Objects Class: Car Object: a car


 Here is another example of a class:
 class Window { ... }
 Here are some examples of Windows:
Attributes: Attributes:
String model model = "Mustang"
Color color color = Color.YELLOW
int numPassengers numPassengers = 0
double amountOfGas amountOfGas = 16.5

Behaviors: Behaviors:
Add/remove a passenger
Get the tank filled
Report when out of gas

M. El Dick - I2211 M. El Dick - I2211


Class vs. Object Class vs. Object
 A piece of the program’s  An entity in a running  Specifies
the number and  Holds specific values of
source code program types of attributes — the attributes;
same for all of its objects  these values can change
while the program is
running
 Written by a programmer
 Created when the
program is running (by the  Specifies
the possible
method main or another behaviors of its objects  Behaves appropriately
method) when called upon

M. El Dick - I2211 M. El Dick - I2211

Classes and Source Files


Overview of classes  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 By convention, the name
of a class starts with a
class Car
capital letter
{
...
}

In Java, all names are case-sensitive

M. El Dick - I2211 M. El Dick - I2211


Libraries import
 Library classes are organized into packages  Full
library class names include the package
 For example: name
 java.util — miscellaneous utility classes
 For example:
 java.awt.Color
 java.awt — windowing and graphics toolkit
 javax.swing.JButton
 javax.swing — GUI development package

 import lets you refer to library classes by their


short names:
 import javax.swing.JButton;
 ...
Fully-qualified
 JButton go = new JButton("Go");
name

M. El Dick - I2211 M. El Dick - I2211

SomeClass.java

import (cont’d) import ... import statements

 Using a wildcard .*: class SomeClass Class header

 import java.awt.*; Imports all public classes {


 import java.awt.event.*; from awt, awt.event, and
 import javax.swing.*; swing packages Fields

 java.lang is imported automatically into all classes


 Contains commonly used classes: System, Math, Object, Constructors
String, etc.

Methods
M. El Dick - I2211 } M. El Dick - I2211
Classes contain fields Classes contain methods
 Fields describe attributes of objects or data held by them  Methods describe the behavior of objects
class Dog {
Fields usually go first in a class Methods usually go after the fields
class Dog { ...
String name; void bark() {
int age; System.out.println("Woof!");
...rest of the class... }
} }

 Each field has  A method can return a value


 a data type (int, double, String, etc.)  void indicates that the method does not return any value
 a name (name, age, etc.)  A method can take parameters or arguments

M. El Dick - I2211 M. El Dick - I2211

Classes always contain constructors Diagram of program structure


 Special method that “constructs,” or creates a new object of the class File Program
Class
File File
class Dog { Data
String name; This part is the constructor Constructors
int age; File
Data
Dog(String n, int a) {
name = n; Statements
age = a; Methods
}  A program consists of
Data one or more classes
}
Statements  Typically, each class is in
a separate .java file

M. El Dick - I2211 M. El Dick - I2211


Some class declaration
Overview of objects class Circle {
double radius = 1.0;
Circle(){
}
double findArea(){
return radius * radius * 3.14159;
}
}
M. El Dick - I2211 M. El Dick - I2211

Declaring a reference variable Creating an object


Example: Class name Example: Class name

Circle myCircle ; myCircle = new Circle();


.
 Creates a reference variable, but does not create a Circle  Creates an object and puts a reference to that object in
object myCircle

M. El Dick - I2211 M. El Dick - I2211


Declaring/Creating an object Analogy
Example: Class name  object you

Circle myCircle = new Circle();  reference your cell phone number


 reference a slip of paper with your cell phone
 After the program stops running, object myCircle no longer
variable number on it,
exists

M. El Dick - I2211 M. El Dick - I2211

Accessing objects Using constructors


 Referencing the object’s data: Circle(double r) {
radius = r; Constructors are special
myCircle.radius
} methods that are invoked
to construct objects
Field name
 Invoking the object’s method: Circle() {
radius = 1.0;
myCircle.findArea() }
--------------------------------------
Method name myCircle = new Circle(5.0);
myCircle = new Circle();

M. El Dick - I2211 M. El Dick - I2211


Getting started
Getting started  Question:

Where do objects come from?
Answer: They are created by other objects

 Question: Where does the first object come from?


 Answer: They are created by the main method

M. El Dick - I2211 M. El Dick - I2211

Getting started (cont’d) A bad program


class Dog {
String name;
public static void main(String[ ] args) int age;
{
Dog fido = new Dog("Fido", 5); Dog(String name, int age) {
} ….
}
void bark() {
 Thespecial keyword static says that the method main System.out.println("Woof!"); This is how methods are invoked on
belongs to the class itself, not to objects of the class } objects
 main can be “called” before any objects are created
public static void main(String[] args) {
-----------------------
bark(); Dog fido = new Dog("Fido", 5);
} fido.bark();
M. El Dick - I2211 M. El Dick - I2211
}
Class’s Client
More details  Any class that uses class X is called a client of X

Class X Class Y
private fields A client
of X

public constructor(s) Constructs objects of X


public methods and/or calls X’s
private methods methods

M. El Dick - I2211 M. El Dick - I2211

Public vs. Private Private field


 Public constructors and methods of a class constitute its
interface with classes that use it — its clients
Accessible anywhere within the class’s source
code
 All fields are usually declared private — they are hidden from
public class Fraction
clients
{
private int num, denom;
 Static constants occasionally can be public
...
public int multiply (Fraction other)
 Methods that are needed only inside the class are declared
{
private
int newNum = num * other.num;
... Any object can access and modify a
private field of another object of the
same class
M. El Dick - I2211 M. El Dick - I2211
public class MyClass
{
// Private fields: Accessors and Modifiers
private <sometype> myField;
...

// Constructors:
public MyClass (...) { ... } Methods that return values Methods that set values of
... of private fields private fields
// Public methods:
public <sometype> myMethod (...) { ... }
Public
... Accessors’ names often start with get Modifiers’ names often start with set
// Private methods: interface
private <sometype> myMethod (...) { ... }
...
}

 Same method can modify several fields or modify a field and also
return its old or new value
M. El Dick - I2211 M. El Dick - I2211

public class Fraction public void setNum(int x)


{ {
Exercice private int num, denom;
}
num=x;

…. public void setDenom(int x)


 Write accessors and modifiers for the class public int getNum() {
Fraction { denom =x;
return num; }
} }
public int getDenom()
{
return denom;
}

M. El Dick - I2211 M. El Dick - I2211


Constructor Constructor (cont’d)
 More than one constructor for the same class
Method for creating objects of the class
 Different numbers and/or types of parameters

 Often initializes an object’s fields  Often provide a “no-args” constructor


 Does not have a return type (not even void) nor a return
 No parameters (a.k.a. arguments)
value
 May take parameters
 If no constructors, Java provides one default -- no-args
All constructors in a class have the same name — the name of constructor
the class  Allocate memory and set fields to the default values

M. El Dick - I2211 M. El Dick - I2211

public class Fraction public Fraction (int n, int d)


{ {
Exercise private int num, denom; num = n;
denom = d;
public Fraction ( ) }
 Complete Fraction to be able to create the following {
“No-args”
objects : num = 0;
constructor
public Fraction (Fraction other)
 A default fraction with num = 0 & denom =1
denom = 1; {
} num = other.num;
 A fraction with num from user & denom =1 denom = other.denom;
 A fraction with num and denum from user public Fraction (int n) }
 A fraction that copies another fraction { ...
num = n;
denom = 1; } Copy constructor
} Continued

M. El Dick - I2211 M. El Dick - I2211


Constructors : a nasty bug Constructors and keyword this
 Constructors
of a class can call each other using the
public class MyWindow
{ keyword this
... public class Fraction ...
// Constructor: { public Fraction (int p, int q)
public void MyWindow ( ) ... {
{ num = p;
... Compiles fine, but… public Fraction (int n) denom = q;
} the compiler thinks this is a { reduce ();
... method and uses MyWindow’s this (n, 1); }
default no-args constructor } ...
instead ... this.num = n;
this.denom = 1;
this.reduce ();
M. El Dick - I2211 M. El Dick - I2211

Operator new Operator new (cont’d)


 Constructors are invoked using new  You must create an object before you can use it
 Parameters passed to new must match the number, types, and
order of parameters expected by one of the constructors
private Fraction ratio; ratio is set to null

public class Fraction


Fraction f1 = new Fraction ( ); { ... Now ratio refers to a
Fraction f2 = new Fraction (5); public Fraction (int n) ratio = new Fraction (2, 3); valid object
Fraction f3 = new Fraction (4, 6); {
Fraction f4 = new Fraction (f3); num = n;
denom = 1;
... Now ratio refers to another
}
object (the old object is
... ratio = new Fraction (3, 4);
“garbage-collected”)

M. El Dick - I2211 M. El Dick - I2211


References to Objects Passing Parameters
Fraction f1 = new Fraction(3,7); Fraction f1 = new Fraction(3,7);  Primitive data types are always passed “by value”
Fraction f2 = f1; Fraction f2 = new Fraction(3,7);
public class Polynomial
A Fraction {
A Fraction copy
f1 f1 object: double x = 3.0; ...
object:
num = 3 double y = p.getValue ( x ); public double getValue (double u)
num = 3 {
f2 denom = 7
denom = 7
double v;
...
A Fraction } u acts like a
Refer to the same f2 object: } local
object variable in
num = 3 x: 3.0 copy u: 3.0 getValue
M. El Dick - I2211
denom = 7 M. El Dick - I2211

public class Test


{
public double square (double x)
{ Passing Objects
x *= x; x here is a copy of the
return x; parameter passed to square.  Objects are always passed by reference
} The copy is changed, but...
public class Fraction
public static void main(String[ ] args) Fraction f1 = new Fraction (1, 2); {
{ Fraction f2 = new Fraction (5, 17); ...
copy reference
Test calc = new Test ();
double x = 3.0; Fraction f3 = f1.add (f2); public Fraction add (Fraction f)
double y = calc.square (x); {
... the original x ...
System.out.println (x + " " + y);
is unchanged. refers A Fraction
} }
Output: 3 9 to object:
} }
num = 5 refers to the
denom = 17 same object
M. El Dick - I2211 M. El Dick - I2211
Passing Objects (cont’d) Passing Objects
A method can change the object :  thiscan be passed to other constructors and
 passed as a parameter methods as a parameter:
 for which it was called
 Example: panel.setBackround(Color.BLUE);

f1.reduce(); public class ChessGame


{
...
Player player1 = new Player (this);
...

A reference to
this ChessGame
M. El Dick - I2211 M. El Dick - I2211
object

Returning Objects Overloaded Methods


 If return type is a class, method returns a reference to Methods of the same class that have the same name
an object (or null)
but different numbers or types of parameters
public Fraction inverse ()
{
if (num == 0) public void move (int x, int y) { ... }
return null; public void move (double x, double y) { ... }
return new Fraction (denom, num); public void move (Point p) { ... }
}
Often returned object is created in the public Fraction add (int n) { ... }
method using new public Fraction add (Fraction other) { ... }
 The returned object can also come from a parameter
or from a call to another method.
M. El Dick - I2211 M. El Dick - I2211
Overloaded Methods (cont’d) Overloaded Methods (cont’d)
 Returntype alone is not sufficient for distinguishing
public class Circle between overloaded methods
Circle circle = new Circle(5); {…
public void move (int x, int y) public class Circle
circle.move (50, 100);
{ ... } {
public void move (int x, int y)
{ ... } Syntax
Point center = new Point(50, 100); public void move (Point p) error
circle.move (center); { ... }
... public Point move (int w, int z)
{ ... }
...

M. El Dick - I2211 M. El Dick - I2211

static Fields static Fields (cont’d)


 Static = shared by all objects of the class  Can hold a constant shared by all objects of the
 Held in static memory with the class code class
 Can be used to collect statistics or totals for all
 Non-static = belong to an individual object objects of the class
 Held in dynamic memory as objects are created and
discarded public class Product Reserved
{ words:
private static final int NUMBER_TYPES = 100; static
private static int totalSales;
final
...

M. El Dick - I2211 M. El Dick - I2211


static Fields (cont’d) static Methods
 Publicstatic fields are usually global constants  Can access and manipulate a class’s static fields
 Referred to in other classes using “dot notation”:  Cannot access non-static fields or call non-static
ClassName.constName methods of the class
 Static methods are called using “dot notation”:

double area = Math.PI * r * r;


ClassName.statMethod(...)
setBackground(Color.BLUE);
c.add(btn, BorderLayout.NORTH);
double x = Math.random();
double y = Math.sqrt (x);
System.exit();

M. El Dick - I2211 M. El Dick - I2211

public class MyClass


{
public static final int statConst;
private static int statVar;
static Methods (cont’d)
private int instVar;
Static  main is static cannot access non-static fields
... method
or call non-static methods of its class
public static int statMethod(...)
{ public class Hello
statVar = statConst; OK {
statMethod2(...); private int test () { ... }
Error:
instVar = ...; public static void main (String[ ] args)
Errors! non-static method
instMethod(...); { test is called from
} test (); static context
} (main)
}

M. El Dick - I2211 M. El Dick - I2211


Non-static Methods
 Called for a particular object using “dot notation”:
vendor.addMoney(25);
Exercises
die1.roll();

 Can access all fields and call all methods of their


class — both static and non-static

M. El Dick - I2211 M. El Dick - I2211

Exercice 1 Exercise 2
 Add the missing class so  Write a class Item that represents an item in a shop. An item is
that the program class Prg{ identified by a name (and sometimes a description), a price
compiles without errors public static void main( String[] args){ and a code bar (10 digits)
int ii;
Boolean bool; public static void main (String[] args)
Cls obj; {
obj = new Cls(); Item i1 = new Item ("Vodka", “A bottle of Vodka", 5483918746L, 75.5);
obj = new Cls( 0 ); Item i2 = new Item (“Lemon 200g", 5474615361L, 3.25);
ii = Cls.a; }
ii = obj.i;
bool = obj.b;
ii = obj.s ( true );  Write a method that computes the price of any number of
obj.v (); items and applies 10% discount if the number is > 10
}}
M. El Dick - I2211 M. El Dick - I2211
public class Item public Item (String name, long barcode,
{ double price)
private String name, description;
private long barcode;
{
this (name, "", barcode, price); Exercise 3 (using java.lang.Math)
private double price; }
public double getPrice()
public Item (String name, String description, {  Define a class Coin that represents a coin. The class should
long return price; have a no-args constructor and 3 methods with the following
barcode, double price) } signatures:
{ public double getPrice (int q)  public void toss() : to flip the coin
this.name = name; {
 public boolean isHead() : to check if the visible side is head
this.description = description; double tot = price * q;
this.barcode = barcode; if (q > 10)  public boolean isTail() : to check if the visible side is tail
this.price = price; {
} tot = tot * 0.9;
 }  Then write a class with a main method that creates a coin, flips
return tot; it 100 times, counts the total number of heads obtained and
} stores it in a field of Coin
}

M. El Dick - I2211 M. El Dick - I2211

public class Coin public class Program


{ {
private boolean head;
public int nbHeads = 0;
public Coin()
public static void main (String[] args)
{
Exercise 4 (using java.lang.Math)
{ Coin c = new Coin();
toss(); for (int i = 0; i < 100; i++)
} {  Write a function rollFor that simulates rolling a pair
public void toss() c.toss(); of dice until the total on the dice comes up to be a
{ if (c.isHead())
int n = (int) (Math.random() * 2); {
given number
head = (n == 0); c.nbHeads++;  The number that you are rolling for is a parameter to the
}
public boolean isHead()
} function
}
{  The number of times you have to roll the dice is the return
return head; }
} value of the function
}
public boolean isTail()  Use your function in a program that computes and prints
{ the number of rolls it takes to get snake eyes
return ! isHead();
} (Snake eyes means that the total showing on the dice is 2)
}

M. El Dick - I2211 M. El Dick - I2211


static int rollFor( int N ) {
// Precondition: N is between 2 and 12, inclusive otherwise infinite
loop
// Roll a pair of dice repeatedly until the total on the 2 dice is N
Exercise 5
int die1, die2; // Numbers between 1 and 6 representing the dice.
int roll; // Total showing on dice Every time you roll the dice repeatedly, trying to get a given total, the number of rolls it
int rollCt; // Number of rolls made takes can be different. What's the average number of rolls? Write a function
rollCt = 0; getAverageRollCount that performs the experiment of rolling 10000 times.
do {  The desired total is a parameter to the function
die1 = (int)(Math.random()*6) + 1;  The average number of rolls is the return value
die2 = (int)(Math.random()*6) + 1;
 Each individual experiment should be done by calling rollFor()
roll = die1 + die2;
rollCt++; Now, write a main program that will call your function once for each of the possible totals
(2, 3, ..., 12). It should make a table of the results:
} while ( roll != N );
return rollCt; Total On Dice Average Number of Rolls
} ------------- -----------------------
2 35.8382
3 18.0607

M. El Dick - I2211 M. El Dick - I2211

public class DiceRollStats { static double getAverageRollCount( int roll ) {


int rollCountThisExperiment; // Number of rolls in one experiment.
static final int NUMBER_OF_EXPERIMENTS = 10000; int rollTotal; // Total number of rolls in all the experiments.
double averageRollCount; // Average number of rolls per experiment.
public static void main(String[] args) { rollTotal = 0;
double average; // The average number of rolls to get a given total for ( int i = 0; i < NUMBER_OF_EXPERIMENTS; i++ ) {
System.out.println("Total On Dice Average Number of Rolls"); rollCountThisExperiment = rollFor( roll );
System.out.println("------------- -----------------------"); rollTotal += rollCountThisExperiment;
for ( int dice = 2; dice <= 12; dice++ ) { }
average = getAverageRollCount( dice ); averageRollCount = ((double)rollTotal) / NUMBER_OF_EXPERIMENTS;
System.out.println(dice); return averageRollCount;
System.out.println(" "); }
System.out.println (average);
}
} //… cont’d on next slide
//… cont’d on next slide

M. El Dick - I2211 M. El Dick - I2211


static int rollFor( int N ) {
int die1, die2; // Numbers between 1 and 6 representing the dice.
int roll; // Total showing on dice.
int rollCt; // Number of rolls made.
rollCt = 0;
do {
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
roll = die1 + die2;
rollCt++;
} while ( roll != N );
return rollCt;
}

} // end DiceRollStats

M. El Dick - I2211

You might also like