Classes and Objects
Classes and Objects
1
What do we know so far?
Primitives: int, float, double, boolean, char
Variables: Stores values of one type.
Arrays: Store many of the same type.
Control Structures: If-then, For Loops.
Methods: Block of code that we can pass
arguments to and run multiple times.
Is this all we want?
2
Object-Oriented Programming
Programming using objects
An object represents an entity
Real world object: String, car, watch, …
Abstract object: client, server, network
connection, …
Objects have two parts:
State: Properties of an object.
Behavior: Things the object can do.
3
Objects
Car Example:
State: Color, engine size, automatic
Behavior: Brake, accelerate, shift gear
Person Example:
State: Height, weight, gender, age
Behavior: Eat, sleep, exercise, study
4
What is an Object?
An Object has two primary components:
state – properties of the object
Examples
object state behavior
dog breed, isHungry eat, bark
grade book grades mean, median
light on/off switch
5
Objects in Java
A class defines a new type of Object
class LightSwitch {
} 6
Fields
An Object's state is stored in variables
called fields
Fields are declared (and optionally
initialized) inside the braces of the class
Light switch example with a field . . .
class LightSwitch {
boolean on = true;
} 7
Methods
true
false
12
Person Example
class Person {
String name = "Jamal";
int age = 26;
String getName() { return name; }
Person(String n, int a) {
name = n;
age = a;
}
// . . .
}
Now we can construct Kebede as follows:
Person kebede = new Person("Kebede", 22);
16
Default Constructor
When you do not write a constructor in a
class, it implicitly has a constructor with no
arguments and an empty body
class LightSwitch {
boolean on;
LightSwitch() {
on = true;
}
LightSwitch(boolean o) {
on = o;
}
} 18
Multiple constructor example 2
class C2{
int a,b;
C2()//no argument passing constructor
{
a=b=0;
}
C2(int x)//one argument passing constructor
{a=b=x;}
C2(int x, int y)//two arg passing constr
{ a=x;
b=y;
}
19
Multiple constructor example 2…
void display()
{
System.out.println("a and b"+a+b);
}}
Class Example{
Public static void main(String[] args){
C2 o1=new C2();//no arg passing consr calling
C2 o2=new C2(100);//one arg…
C2 o3=new C2(10,20);//two arg…
o1.display();
0
o2.display(); 100
o3.display(): 10 and 20
20
This Keyword
Instance can refer to itself with the keyword this
class LightSwitch {
boolean on;
LightSwitch() {
this.on = true; //(same as
on=true;)
}
LightSwitch(boolean on) {
this.on = on;
}
} 21
Cascading Constructors
A constructor can call another constructor with
this(arguments)
class LightSwitch {
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
22
Classes summary
Classes have:
fields to store the state of the objects in the class and
methods to provide the operations the objects can
perform.
We construct instances of a class with the keyword
new followed by a call to constructor method of the
class.
Apple(double price) {
this("green", price);
}
E.g:
public double volume(double l,double w,
double h);//three parameters
public double volume(double l);//one
parameter
27
Method overloading...
Changing the return type doesn’t affect whether
the overloading is valid or not.
Changing the order of parameters is valid.
E.g-
public void area(int x, int y, long z);
public void area(long a, int b, int c);
28
Illustrating Method overloading
class Shape {
double length,width,area;
void area()
{
length=5;
width=6;
area=(length*width);
System.out.println(“Area is:”+area);
}
29
Illustrating Method overloading...
void area(double l, double w){
length=l;
width=w;
area=(length * width);
System.out.println(“Area is:”+area):
}}
Class ShapeArea{
public static void main(String[] args){
Shape s=new Shape();
s.area();
s.area(10,10);}} // output= Area is 30.0
Area is 100.0
30
Constructor overloading
We can have several constructors but with a
different parameter with in a class.
The property by which a class can have multiple
constructors is called constructor overloading.
E.g:
Class Area{
double length,width,area;
31
Constructor overloading...
Area(){
length=5;
width=6;
area=(length*width);
System.out.println(“Area is:”+area);
}
Area(double l, double w){
length=l;
Width=w;
area=(length * width);
System.out.println(“Area is:”+area):
32
Constructor overloading...
Area(double l){
length=l;
area=(length * length);
System.out.println(“Area is:”+ area);
}}
class ShapeArea{
public static void main(String[] args){
Area a1=new Area();
Area a2=new Area(10,10);
Area a3=new Area(10);}}
Output: Area is: 30.0
Area is: 100.0 Area is: 100.0 33
Equality Quiz 1
Is (a == b) ?
int a = 7;
int b = 7;
Answer: Yes
Is (g == h) ?
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
Answer: No
34
Primitives vs Objects
Two datatypes in Java: primitives and objects
g h
"Jamal" "Jamal"
26 26
37
Reference Equality
kebe1 == kebe2 because kebe1 and
kebe2 hold references to the same object
Person kebe1 = new Person("Kebe", 23);
Person kebe2 = kebe1;
kebe1
" Kebe"
23
kebe2
38
Equality Quiz 2
true or false?
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
Person Abe1 = new Person("Abe", 23);
Person Abe2 = Abe1;
a) g == h false
b) g.getAge() == h.getAge() true
c) Abe1 == Abe2 true
d) Abe1.getAge() == Abe2.getAge(); true
39
Static and Final
40
MyMath Example
m.square(5);
42
MyMath Output
The results of invoking square() method on
instances m and n are the same:
m: value of PI is 3.14159
m: square of 5 is 25
n: value of PI is 3.14159
n: square of 5 is 25
46
The final keyword
We declared PI as
public static double PI = 3.14159;
but this does not prevent changing its value:
MyMath.PI = 999999999;
49
Static Square Method
We also added the word "static" to the
declaration of the method square():
52
Static Field Examples
Constants used by a class
(usually used with final keyword)
53
Static Method Examples
For methods that use only the arguments and
therefore do not operate on an instance
public static double pow(double b, double p)
// Math class, takes b to the p power
public double i;
public void display():
57
Visibility control…
Private access: Granted using the private
key word,
It is the most restrictive of the four access
specifiers.
It can’t be accessed outside the class. E.g.,
private double i;
private void sum():
58
Visibility control…
Protected: Protected access granted
using the protected key word.
A protected member is accessible to any
other class in the same package and also
child classes.
no matter which class is the child with in.
protected double i;
protected void callme():
59
Visibility control…
Default access: is also referred to as a
package access.
You grant default access by not using
anyone of the three access specifiers.
A member with default access is
accessible to any other classes in the
same packages.
double i;
void callme():
60