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

Object Oriented Concepts

Object oriented programming groups data and operations together into classes. The three main principles of OOP are encapsulation, inheritance, and polymorphism. Encapsulation hides internal details and controls access to data, inheritance allows for code reuse and specialization through subclasses, and polymorphism allows the same operations to work on different types of objects.

Uploaded by

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

Object Oriented Concepts

Object oriented programming groups data and operations together into classes. The three main principles of OOP are encapsulation, inheritance, and polymorphism. Encapsulation hides internal details and controls access to data, inheritance allows for code reuse and specialization through subclasses, and polymorphism allows the same operations to work on different types of objects.

Uploaded by

eliza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Object Oriented Concepts

Objectives
After this chapter, you should be able to:
Determine the differences between procedural and Object –
Oriented programming.
Learn about the 3 main principles of Object – Oriented
programming.
◼ Encapsulation
◼ Inheritance
◼ Polymorphism
Know more about classes and objects.
Procedural vs. Object-Oriented
Programming
The unit in procedural programming is function, and unit in
object-oriented programming is class
Procedural programming concentrates on creating functions,
while object-oriented programming starts from isolating the
classes, and then look for the methods inside them.
Procedural programming separates the data of the program from
the operations that manipulate the data, while object-oriented
programming focus on both of them

figure1: procedural figure2: object-oriented


Problem Description
“ …customers are allowed to have
different types of bank accounts,
deposit money, withdraw money and
transfer money between accounts”
Procedural Approach
bool MakeDeposit(int accountNum,float amount);
float Withdraw(int accountNum,float amount);

struct Account {
char *name;
int accountNum;
float balance;
char accountType;
};
Procedural Approach cont’d
Focus is on procedures
All data is shared: no protection
More difficult to modify
Hard to manage complexity
Procedural vs. Object-Oriented
Procedural Object Oriented

Withdraw, deposit, transfer Customer, money, account


Procedural vs Object-Oriented
UNION CLASS

Data 1 Data 1
Data 2 Proc 1
Data 3
Data 2
PROCEDURE
Proc 2
Proc 1
Proc 2 Data 3
Proc 3 Proc 3
Procedural Style vs OOP Style

Procedural Style
• A client is responsible for invoking appropriate supplier
functions to accomplish a task.

OOP Style
• Suppliers are responsible for conforming to the standard
interface required for exporting the desired functionality to a
client.
Object Oriented Programming
Data and operations are grouped together

Account Interface:

Withdraw Set of available operations


Deposit
Transfer
Encapsulation
Encapsulation hides the internal structure and operations of an
object behind an interface.

Ex. A bank ATM is an object that gives its users cash.


The ATM hides (encapsulates) the actual operation of withdrawal
from the user.

The interface (way to operate the ATM) is provided by the


keyboard functions, screen, cash dispenser, and so on.

Bypassing the encapsulation in object-oriented programming is


impossible.
Encapsulation
Controlling visibility of names
Enables enforcing data abstraction
◼ Conventions are no substitute for enforced constraints.
Enables mechanical detection of typos that manifest as
“illegal” accesses. (Cf. problem with global variables)
Encapsulation
Encapsulation: public, private and protected
◼ Public – accessible by anyone

◼ Private – accessible by the same class only

◼ Protected – accessible by the same class, the subclasses,

descendent classes, and classes of the same package


Advantages of Encapsulation
Protection
Consistency
Allows change
Classification

Animal

Mammal Reptile

Rodent Primate Cats

Mouse Squirel Rabbit


Classification

Account

Checking Account Savings Account

Value First Select Access First Interest


Inheritance
There may be a commonality between different classes.
Define the common properties in a superclass.
Variants of the same class, each (subclass) preserves the
methods and data of the parent class (superclass) while
defining their own implementation and add their own
methods and data.
A class which is a subtype of a more general class is said to
be inherited from it.
The sub-class inherits the base class’ data members and
member functions
A sub-class has all data members of its base-class plus its
own
A sub-class has all member functions of its base class (with
changes) plus its own
Inheritance is meant to implement sub-typing
Inheritance
Savings account -> Account <- Checking account
The subclasses use inheritance to include those properties.
Using the “Is-a-Kind-of” Relationship
A subclass object “is-a-kind-of” superclass object.
A subclass must have all the attributes and behaviors of the
superclass.
Account <- Savings account
Inheritance : Subclasses
Code reuse
 derive Colored-Window from Window
(also adds fields/methods)
Specialization: Customization
 derive bounded-stack from stack
(by overriding/redefining push)

Generalization: Factoring Commonality


◼ code sharing to minimize duplication
◼ update consistency
Abstraction
Management of complexity
Hierarchical classification:

is-a relationship: inheritance


has-a relationship: containment
What is a good class ?
A class abstracts objects
A class should be non-trivial in the
context of the program (has data
structures and operations different from
other classes)
Polymorphism (many forms)
Many forms of the same operations
The ability to request an operation with the same meaning to
different objects. However, each object implements the
operation in a unique way.
The principles of inheritance and object substitution.
One interface
Multiple implementations
Inheritance
Method overloading
Polymorphism (many forms)
Integrating objects that exhibit common behavior and can
share “higher-level” code.
Unifying heterogeneous data.

◼ E.g., moving, resizing, minimizing, closing, etc windows


and colored windows
Polymorphism
Polymorphism
◼ Calling the same method, the action is different depending
on what class the object belongs to
Polymorphism
Bank Account

Deposit()
Balance:

Saving Current
Account Account

Deposit() Deposit()
Balance: Balance:

Min. balance req: # Checks issued


$1000
Summary
What is Object Oriented Programming?
Object-oriented programming is a method of
implementation in which programs are
organized as cooperative collections of
objects, each of which represents an instance
of some class, and whose classes are all
members of one or more hierarchy of classes
united via inheritance relationships
static keyword (w/ methods)
class Math {
public static double sqrt(double x) {
// calculate
return result;
}
}
class MyApp {
public static void main(String [] s ) {
double dd;
dd = Math.sqrt(7.11);
}
}

27
Constructor
For proper initialization, a class must provide a
constructor.
A constructor is called automatically when an object
is created:
◼ It is usually declared public.
◼ It has the same name as the class.
◼ It must not specify a return type.
The compiler supplies a no-arg constructor if and
only if a constructor is not explicitly provided.
◼ If any constructor is explicitly provided, then the compiler
does not generate the no-arg constructor.
Is a method that is called when a new object is
created
Can perform any action you write its definition
Defining & overloading Constructors
public class Movie{
private String title;
private String rating = “PG”;

public Movie(){
title = “One More Chance”;
}
public Movie(String newTitle){
title = newTitle;
}
}
----------
Movie mov1=new Movie();
Movie mov1=new Movie(“2 fast 2 furious”);
The this Method
When defining a constructor, another common
action is to call one of the other constructors
in the same class.
Sharing Code between Constructors
Movie mov1 = new Movie();
Movie mov2 = new Movie(“A”);
-----
public class Movie{
private String title, rating;

public Movie(){
this(“G”);
}
public Movie(String newRating){
rating = newRating;
}
}
Sharing Code between Constructors
class Weight {
int lb, oz;
public Weight (int a, int b) { lb = a; oz = b;}
public Weight (int x) { this( x, 0); }
}
How to extend classes?
Inheritance: mechanism for extending behavior of
classes; leads to construction of hierarchy of classes
What happens when class C extends class D:
◼ Inherits instance variables
◼ Inherits static variables
◼ Inherits instance methods
◼ Inherits static methods
◼ C can:
 Add new instance variables
 Add new methods (static and dynamic)
 Modify methods (only implementation)
 Cannot delete anything
Inheritance
---Parent class
class Person{
Person(){
System.out.println(“James”);
}
}
---Sub class
public class Driver extends Person{
Driver(){
System.out.println(“Bond”);
}
public static void main(String args []){
Driver d = new Driver();
}
}
Super method
---Parent class
class Person{
private String name;
Person(){
this(“Juan”);
}
Person(String n){
name=n;
}
}
---Sub class
public class Driver extends Person{
Driver(){
super();
}
}
Encapsulation
Applying Encapsulation in Java
Instance variables must be declared as private.
Only instance methods can access private instance
variables.
private decouples the interface of the class from its
internal operation.

Movie mov1 = new Movie();


String rating = mov1.getRating();
String r = mov1.rating; //error: private
Polymorphism
Using the process of dynamic binding to
allow different objects to use different
method actions for the same method
name.
Polymorphism
class A extends Object{
public void m(){System.out.println("m()");}
==========
class B extends A{
public void m(int x){
System.out.println("m(int x)");
}
public void m(String y){
System.out.println("m(String y)");
}
==========
class Poly01{
public static void main( String[] args){
B var = new B();
var.m();
var.m(3);
var.m("String");
}
Activity
Create a superclass named Person with at least 10
properties. Provide corresponding accessors (getters)
and mutators (setters) for each of the methods.
Create a subclasses named Employee and Student
with an additional 2 properties of each subclasses
that inherits the superclass Person.
Create a class Driver, that will take care in creating
objects. Two (2) objects for the class Employee and
Student as well.
Display all employees and students.
GUI Programming in Java
(AWT and Event Handling)
Java GUI
The Swing package
and AWT package
provides capability of import javax.swing.*;
public class sample {
building cross- public static void main(String args []){
platform GUI JFrame frame = new JFrame("WELCOME");
JLabel lbl = new JLabel("Hello World");
Classes like JForm,
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton, JCheckBox, frame.getContentPane().add(lbl);

JMenuItem can be frame.setSize(170,100);


frame.setVisible(true);
used to create basic }

components }
Java GUI
Action Listener: tells the program to listen to a certain event

public class Beeper ... implements ActionListener {


...
//where initialization occurs:
button.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
...//Make a beep sound...
}
}
Java GUI

A simpler solution
◼ Use NetBeans (or other IDEs) to build GUIs
Java GUI
Java GUI
Java GUI
Java GUI
Java GUI

You might also like