Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
74 views

Classes and Objects

Classes and objects are fundamental concepts in object-oriented programming. A class defines the type of an object and includes fields to represent an object's state and methods to represent its behavior. Objects are instances of classes that are created using the new keyword. Constructors initialize an object's state and can be overloaded. Methods can also be overloaded if they have different parameter types but the same name. This allows polymorphism at compile time.

Uploaded by

Asib Kassaye
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Classes and Objects

Classes and objects are fundamental concepts in object-oriented programming. A class defines the type of an object and includes fields to represent an object's state and methods to represent its behavior. Objects are instances of classes that are created using the new keyword. Constructors initialize an object's state and can be overloaded. Methods can also be overloaded if they have different parameter types but the same name. This allows polymorphism at compile time.

Uploaded by

Asib Kassaye
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 60

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

 behavior – operations the object can perform

 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

 To create an Object type to represent a


light switch . . .

class LightSwitch {

// state and behavior here

} 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

 An Object's behavior is defined by its


methods

 Methods, like fields, are written inside


the braces of the class

 Methods can access the fields (the state)


of their object and can change them
8
Light Switch Example
class LightSwitch {

boolean on = true; // field

boolean isOn() { // returns


return on; // the state
}

void switch() { // changes


on = !on; // the state
}
} 9
Constructing Objects
 We use the new keyword to construct a
new instance of an Object

 We can assign this instance to a variable


with the same type of the Object

LightSwitch ls = new LightSwitch();

 Note: classes define new datatypes !


10
Using Fields and Methods
LightSwitch ls = new LightSwitch();
 To access the field of an instance of an
Object use instance.field
ls.on;

 To access the method of an instance use


instance.method(arguments)
ls.isOn();
ls.switch();
11
Example Using Light Switch

 What does this main method print out?


public static void main(String[] args){
LightSwitch ls = new LightSwitch();
System.out.println(ls.on);
ls.switch();
System.out.println(ls.isOn());

true
false
12
Person Example
class Person {
String name = "Jamal";
int age = 26;
String getName() { return name; }

void setName(String n) { name = n; }

int getAge() { return age; }

void setAge(int a) { age = a; }

boolean smellsGood(){return true;}


}
13
Constructing Person Objects
 To create an instance of the Person class
with a name of "kebede" and an age of 22
Person kebede = new Person();
kebede.setName("kebede");
kebede.setAge(22);

 Can we create a Person that has the name


Kebede and the age 22 from the moment it
is created?
 Answer: Yes! 14
Constructors
 Constructors are special methods used to
construct an instance of a class

 They have no return type

 They have the same name as the class of the


Object they are constructing

 They initialize the state of the Object

 Call the constructor by preceding it with the


new keyword
15
Person Constructor
class Person {
String name;
int age;

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 {

// Leaving out the constructor


// is the same as . . .
LightSwitch() {}
}
 Result: every class has a constructor
17
Multiple Constructors
 A class can have multiple constructors
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.

 If you do not provide a constructor, the class will


have one with no arguments and no statements by
default.
23
Apple Example
class Apple {
String color;
double price;

Apple(String color, double price) {


this.color = color;
this.price = price;
}

Apple(double price) {
this("green", price);
}

String getColor() { return color; }


double getPrice() { return price; }
void setPrice(double p) { price = p; }
} 24
Apple Quiz
 What will these lines print out?

Apple a = new Apple("red", 100.0);


System.out.println(a.getColor()); red
System.out.println(a.getPrice()); 100.0
a.setPrice(50.5);
System.out.println(a.getPrice()); 50.5

Apple b = new Apple(74.6);


System.out.println(b.getColor()); green
System.out.println(b.getPrice()); 74.6
b.setPrice(a.getPrice());
System.out.println(b.getPrice()); 50.5
25
Method overloading
 Java allows a method to be overloaded.
 Method overloading occurs when a class has two
or more methods with the same name but different
parameter lists.
 On calling a method,
 at first java matches up the method name
 and then the number and type of parameter to decide
which one of the definition to execute.
 This process is known as compile time
polymorphism.
26
Method overloading...
 In method overloading, we need to remember
certain points:
 You can overload a method as long as the
parameter lists are distinct (i.e. number of
parameters is different.)

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);

 If you simply change the name of parameters, it


is not valid.

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

Primitives: byte, short, int, long, double, float,


boolean, char
== tests if two primitives have the same value

Objects: defined in Java classes


== tests if two references refer to the same
object 35
References
 The new keyword always constructs a
new unique instance of a class
 When an instance is assigned to a
variable, that variable is said to
hold a reference or point to that object
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);
 g and h hold references to two different
objects that happen to have identical state
36
Reference Inequality
 g != h because g and h hold references
to different objects
Person g = new Person("Jamal", 26);
Person h = new Person("Jamal", 26);

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

public class MyMath {


public double PI = 3.14159;

public double square (double x) {


return x * x;
}

public static void main(String[ ] args) {


MyMath m = new MyMath();
System.out.println("m: value of PI is " + m.PI);
System.out.println("m: square of 5 is " + m.square(5));

MyMath n = new MyMath();


System.out.println("n: value of PI is " + n.PI);
System.out.println("n: square of 5 is " + n.square(5));
}
} 41
Objects Review
 In Example 1, to calculate the square of 5 we
need to create an instance of MyMath class:

MyMath m = new MyMath();

 Then we invoke it’s square() method with the


argument 5:

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

 square() behaves the same no matter which


instance it is called on.

 So . . . why not have one square() method


for the entire class?
43
Also . . .
 The value of PI = 3.14159 is the
same for all instances of MyMath class.

 Why do we need to store a value of PI


separately for each instance of MyMath?

 Instead, can we have only one common


value of PI for the whole MyMath class?
44
MyMath with static
public class MyMath {

// add keyword "static" to field declaration


public static double PI = 3.14159;

// add keyword "static" to method declaration


public static double square (double x) {
return x * x;
}

// main method is always declared "static"


public static void main( String[ ] args) {
// MyMath m = new MyMath(); - No longer need this line!
// MyMath n = new MyMath(); - No longer need this line!

// Now invoke square() method on the MyMath class


System.out.println("Value of PI is " + MyMath.PI);
System.out.println("Square of 5 is" + MyMath.square(5));
}
} 45
Static Pi Field
 We added word static to the declaration of
the final variable PI:

public static double PI = 3.14159;

 It means that now we have only one value of


variable PI for all instances of MyMath class;
PI is now a class data field

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;

 Use keyword final to denote a constant :


public static final double PI = 3.14159;

 Once we declare a variable to be final, it's


value can no longer be changed!
47
MyMath with static & final
public class MyMath {

// add keyword final to field declaration


public static final double PI = 3.14159;

public static double square (double x) {


return x * x;
}

public static void main( String[ ] args) {


System.out.println("Value of PI is " +
MyMath.PI);
System.out.println("Square of 5: " +
MyMath.square(5));
}
}
48
Static Fields

 Only one instance of a static field data for


the entire class, not one per object.

 "static" is a historic keyword from C/C++

 "Class fields" is a better term


 As opposed to "instance fields"

49
Static Square Method
 We also added the word "static" to the
declaration of the method square():

public static double square(double x) {


return x * x;
}

 Now the method square() is shared by all


instances of the class—only one square
method for the class, not one for each instance.
50
Static Methods
 Static methods do not operate on a
specific instance of their class

 Have access only to static fields and


methods of the class
 Cannot access non-static ones

 "Class methods" is a better term


 As opposed to "instance methods"
51
Java's Math Class
 Let's take a look at Java's Math class in the API

 You cannot create an instance of the Math Class,


it's just a place to store useful static methods

 All the methods and fields are static:


Math.sqrt(16)
Math.PI

52
Static Field Examples
 Constants used by a class
(usually used with final keyword)

 Have one per class; don’t need one in each object


public static final double TEMP_CONVERT= 1.8;

 Constants are all capital letters by tradition (C, C++)


 For example: PI , TEMP_CONVERT etc.

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

 For methods that only need static data fields

 Main method in the class that starts the


program
 No objects exist yet for it to operate on!
54
QUIZ

Should it be static or non-static?

 Speed of light field static


 getName() method in a Person class non
 A sum method that returns the static
resulting of adding both its arguments
 Width data field in a Rectangle class non
55
Visibility control
 Every member of a class:
- The field
- Methods and
- Constructors
 Has an access specifier that determines
who has access to the member.
 Java provides four levels of access for
members of a class.
56
Visibility control…
 Public access: Granted using the public
keyword.
 It is referred to as universal access b/c
public members are accessible to any
other objects. For example:

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

You might also like