0% found this document useful (0 votes)
37 views37 pages

01-303 F22 Object-Oriented Programming

Uploaded by

Rawan Khaled
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)
37 views37 pages

01-303 F22 Object-Oriented Programming

Uploaded by

Rawan Khaled
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/ 37

Data Structures

CMPS 303
Dr. Osama Halabi

Object Oriented Programming

Copyright © Some of the slides are


adopted from colleagues’ slides.
© 2014 Goodrich, Tamassia, Goldwasser
Copyright © 2014, 2008 Pearson Education,
© 2011 The McGraw-Hill Companies, Inc. Inc. Publishing as Pearson Addison-Wesley
All rights reserved
Copyright © 2009 Pearson Education, Inc.

Data Structures
Publishing as Pearson Addison-Wesley

CMPS 303
Dr. Osama Halabi

Lecture
Text
Text
2
11
Chapter 4
Chapter 2
Making Decisions
Object-Oriented Programming
If, if/else, if/else if, switch
Game Design & Development 2 © Osama Halabi
Concept
✤ Object-Oriented Programming (OOP) = Designing the
application based on the objects discovered when
analyzing the problem
✤ A class is code that describes a particular type of object. It
specifies the data that an object can hold (attributes), and
the actions that an object can perform (methods).
✤ A class is a programmer-defined data type and
objects are variables of that type
A class contains attributes and methods
Game Design & Development 3 © Osama Halabi
Class vs. Object
Class

Template for
making Objects

Class is a “template” or
Object is an actual
“blueprint” that
describes the structure instance of a class.
of its objects (properties It holds values for
and methods). the properties.

Game Design & Development 4 © Osama Halabi


BankAccount Example

deposit An Object has:


✤Attributes –
Private data:
withdraw accoutNumber

getBalance
information about
balance
getOnwer
the object
setOnwer
✤Methods – functions
the object can
BankAccount contains attributes
perform
and methods
Game Design & Development 7 © Osama Halabi
Class Example
private data
Methods
Attributes

withdraw
deposit

accountNo
accountName
balance

getBalance

….. Bank Account Object

Game Design & Development 6 © Osama Halabi


Using a class: Instantiation
✤To use a class you must create an object from a class (this is called
instantiation)
✤ An object is an instance of a class
✤ Instantiation = Object creation with new
keyword
e.g., Account myAcc = new Account();
This declares myAcc object of type Account. The object is then
created using the new keyword
✤ Memory is allocated for the object’s attributes as defined in the
class
Data Structures 7 © Osama Halabi &  2004 Pearson Education, Inc. &
© 2011 The McGraw-Hill Companies, Inc. All rights reserved.
Instantiation

Data Structures © Osama Halabi &  2004 Pearson Education, Inc. &
8 © 2011 The McGraw-Hill Companies, Inc. All rights reserved.
UML Diagram and Java Code

Rectangle r1=new Rectangle();


Rectangle r2=new Rectangle(2,5);

Game Design & Development 9 © Osama Halabi


Class Members

Instance Methods Constructors


Variables

Instance Variables
Constructors

Methods

Game Design & Development 10 © Osama Halabi


Instance Variables

Variables that are defined inside the class but outside all methods.

Instance variables have default values. For numbers, the default


values is 0, for Booleans it is false, for objects its null

Instance variables are created when an object is created and


destroyed when the object is destroyed.

Game Design & Development 11 © Osama Halabi


Methods
✤ Definition
✦ Functions that are defined inside a class. Also called
“member functions”.
✤ Variables defined inside a method are called local
variables. They have no default initial values, so they
should be initialized before they are used.
✤ Method overloading: when a class has two or more
methods by the same name but different parameters,
it is called method overloading
Game Design & Development 12 © Osama Halabi
Constructors
✤ Definition
✦ Constructors = ‘Methods’ used to initialize an object’s attributes
when it is created
✦ Constructor is a special initialization method called when an
object is created with new.
Constructor has the same name as the class
and has no return type (not even void).
public class MyClass {
public MyClass(Type paramName, … ) { … }
}

Class can have more than one constructor (overloading).


Game Design & Development 13 © Osama Halabi
Constructor Example
✤ Constructor = special public class Account {
method that handles the private int id;
private String name;
object initialization private double balance;

✤ A constructor is used to Constructor

initialize the objects during public Account (int id, String name,
double balance) {
object construction. this.id = id;
this.name = name;

✤ Example
this.balance = balance;
}
Account saraAcct = new
Account(123, "Sara", 100.0);

Game Design & Development 14 © Osama Halabi


Access Modifier
✤Java language has four access modifier to control access
to classes, attributes, methods and constructors.
✦ Private: visible only within the class
✦ Default (no modifier): visible only within the same package.
✦ Protected: visible within the same package and to sub classes
outside the package.
✦ Public: visible everywhere

Game Design & Development 15 © Osama Halabi


Access Modifiers Summary

Game Design & Development 16 © Osama Halabi


Relationships between classes

Relationships between classes

Composition Inheritance

Game Design & Development 17 © Osama Halabi


Composition
Student has a birthdate “date”

Game Design & Development 18 © Osama Halabi


Inheritance
Class A Class extends other Student
class
Is a
Class B Class C Undergraduate Graduate

A class that is derived from another class is called a subclass

The class from which the subclass is derived is called a superclass

Every class has one and only one direct superclass (single inheritance). Java does
not support multiple inheritance
Every class in Java implicitly inherits class Object
Game Design & Development 19 © Osama Halabi
Static Variable
vs
Instance Variable

20
Instant Variable
Instance variables are created when an object is created with the use of the
key word 'new' and destroyed when the object is destroyed.

The instance variables are visible for all methods, constructors and block in
the class. Normally it is recommended to make these variables private
(access level).

Instance variables have default values. For numbers the default value is 0,
for Booleans it is false and for object references it is null. Instance variables
can be accessed directly by calling the variable name inside the class.

Game Design & Development 21 © Osama Halabi


Instance Variables Example
public class Car {
private String model; OUTPUT:
public Car (String model){ Car Model = Civic
this.model = model;
} Car Model = Pilot
public void printModel () {
System.out.println("Car Model = " + model);
}
}
public class CarTesting {
public static void main(String[] args) {
Car honda = new Car("Civic");
Car toyta = new Car("Pilot");
honda.printModel();
toyta.printModel();
}
}
Game Design & Development 22 © Osama Halabi
Static Variable
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.

There would only be one copy of each Every instance of the class share the same static variable
class variable per class, regardless of Any change in the static variable can be seen by all objects
how many objects are created from it. (instances)

Static variables are created when the program starts and destroyed when the
program stops.

Static variables can be accessed by calling with the class name.


ClassName.VariableName These variables are created when the program starts
and destroyed when the program stops.
Game Design & Development 23 © Osama Halabi
Static Variables Example
public class Car {
private static String model; OUTPUT:
public Car (String model){ Car Model = Pilot
Car.model = model;
}
Car Model = Pilot
public void printModel () {
System.out.println("Car Model = " + model);
}
}
public class CarTesting {
public static void main(String[] args) {
Car honda = new Car("Civic");
Car toyta = new Car("Pilot");
honda.printModel();
toyta.printModel();
}
}
Game Design & Development 24 © Osama Halabi
Static Methods
vs
Instance Methods

25
Static Methods
✤ A static method belongs to the class rather than the object (instance) of the class.
✦ Also known as “class methods” (vs. “instance methods”)
✤ A static method can only access the static attributes.
✦ Static methods can’t access instance methods and instance variables directly.
✤ A static method can be called without the need for creating an instance of
the class.
✦ You call a static method through the class name

ClassName.functionName(arguments);
✦ For example, the Math class has a static method called cos
‣ You can call Math.cos(3.5) without creating an object of the Math class
✤ E.g., the main method is a static method so the system can call it without first
creating an object
Game Design & Development © Osama Halabi
Static Method Example
class Calculator {
public static void printSum(int a, int b) {
System.out.println("Sum = " + (a + b));
}
}
public class Main {
public static void main(String[] args) {
Calculator.printSum(5, 10);
printHello();
}
public static void printHello () {
System.out.println("Hello");
}
}
Game Design & Development 27 © Osama Halabi
Generics
Generic Method
public static void print(Employee x[])
To write a method to print {
an array of employees. for (int i=0;i<x.length;i++)
System.out.println(x[i]);
}

public static void print(Student x[])


To print an array of students {
for (int i=0;i<x.length;i++)
System.out.println(x[i]);
}
Instead of writing separate
method to print each object public static <E> void print(E x[])
type, we can write a generic {
for (int i=0;i<x.length;i++)
method that prints an array
System.out.println(x[i]);
of any type of objects. }
Game Design & Development © Osama Halabi
Generics to avoid casting

✤Java includes support for writing generic classes and methods that can
operate on a variety of data types while often avoiding the need for
explicit casts.
✤The generics framework allows us to define a class in terms of a set of
formal type parameters, which can then be used as the declared type for
variables, parameters, and return values within the class definition.
✤Those formal type parameters are later specified when using the generic
class as a type elsewhere in a program.

Game Design & Development 30 © Osama Halabi


Syntax for Generics
✤Often, we wish to treat a pair of related values as a single object, for
example, so that the pair can be returned from a method. A solution is to
define a new class whose instances store both values:

ObjectPair bid = new ObjectPair("ORCL", 32.07);


Game Design & Development 31 © Osama Halabi
Syntax for Generics
String stock = bid.getFirst(); // illegal; compile error

✤This represents a narrowing conversion from the


declared return type of Object to the variable of type
String.
✤Instead, an explicit cast is required, as follows:
String stock = (String) bid.getFirst(); // narrowing cast: Object to String
✤With the classic style for generics, code became rampant with such
explicit casts.
Game Design & Development 32 © Osama Halabi
Syntax for Generics
✤Types can be declared using generic names:

✤They are then instantiated using actual types:


Pair <String, Double> bid; This process is known as
bid = new Pair<> ("ORCL", 32.07); type inference, and was
introduced to the generics
String stock = bid.getFirst(); framework in Java SE 7.
double price = bid.getSecond();
Game Design & Development 33 © Osama Halabi
Generics and Arrays

Pair<String,Double>[] holdings;
/*
holdings = new Pair<String,Double>[25]; // illegal; compile error
*/
holdings = new Pair[25]; // correct, but warning about unchecked cast
holdings[0] = new Pair<>("ORCL", 32.07); // valid element assignment

Game Design & Development 34 © Osama Halabi


Generic Class (1)
We can define our own classes with generics type. A generic type is a class or interface that
is parameterized over types. We use angle brackets (< >) to specify the type parameter.
public class WaitingList<E> {
private E[] a;
private int count;

public WaitingList(int s)
{
a=(E[])new Object[s];
count=0;
}

public void add(E e)


{
a[count]=e;
count++;
}
Game Design & Development 35 © Osama Halabi
Generic Class (2)
public E get(int i)
{
if (i<count)
return a[i];
else
return null;
}

public void print()


{
for (int i=0;i<count;i++)
System.out.println(a[i]);
}
}

The object type is specified when creating an object of generic class, for example
WaitingList<Student> ws = new WaitingList<Student>(5);
Note that type parameters can represent only reference types, not primitive types
(like int, double and char).
Game Design & Development 36 © Osama Halabi
END OF

End of
Object Oriented
Programming

You might also like