You are on page 1of 106

Pearson BTEC Level 5 Higher National Diploma in

Computing (Software Engineering)

Unit 20 - Advanced Programming - Y/615/1651

Concepts Of Object Oriented


Programming
Ms. A.M.L. Chamini 1
Learning Outcomes

 Learning Outcome 01: Examine the key components


related to the object-orientated programming paradigm,
analyzing design pattern types

Ms. A.M.L. Chamini 2


Objectives

 Understand what is a Programming Language.

 Identify the compiler and interpreter.

Ms. A.M.L. Chamini 3


• OOP stands for Object-Oriented Programming.
• Procedural programming is about writing procedures or methods that perform
operations on the data, while object-oriented programming is about creating
objects that contain both data and methods.
• Object-oriented programming has several advantages over procedural
programming:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
Ms. A.M.L. Chamini 4
• OOP helps to keep the Java code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less
code and shorter development time
• Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing
the repetition of code. You should extract out the codes that are
common for the application, and place them at a single place and
reuse them instead of repeating it.
Ms. A.M.L. Chamini 5
Object-Oriented Programming Language
 Everything is an object
 A program is a set of objects telling each other what to do
by sending messages
 Each object has its own memory. (Made up by other
objects)
 Every object has a type
 All objects of a specific type can receive the same message.

Ms. A.M.L. Chamini 6


Introduction to Java
• Full-fledged application programming language

• Additional capability as a Web programming language (currently the strength of its


application base)

• A pure OO programming language

• NOT radical or especially new

A.M.L. Chamini
It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection

A.M.L. Chamini
OOP and Java
• Java is a purely an object – oriented language.
• The central idea behind object-oriented programming is to
divide a program into isolated parts called Objects.
• Each object contain two parts.
Data

A.M.L. Chamini
Functions
OOP and Java

• The functions in an object operate on the


data involved in that object.

A.M.L. Chamini
Terminology
• Class- A collection of data and methods that operate on that data
• Method- A group of statements in a class that handle a task.
• Attribute- A property of an instance of a class.
• Interface- A skeleton class.
• Package- A group of logically related codes (classes & interfaces)

A.M.L. Chamini
Class
A class is a blueprint or prototype that defines the variables
and the methods common to all objects of a certain kind

Object
Object is an element or instance of a class which have the
behaviors of their class.
 Data and routines (functions) required to process it are combined into a single entity
called an Object.
 A collection of similar objects is known as a class. (Blueprint of Object).
 In order to clearly understand the idea of objects, lets us now consider an example.
Suppose we are planning a birthday party and we wish to play some songs available in
our compact disk. there is an index card file, in which each card contains a song’s name,
its author and its playing time in the following format.
Song
name

A.M.L. Chamini
 The above mentioned data in the index card file can be used to get the following types of
information about a particular song of interest.
Name of the song ,Name of the Author, Playing time of the song.
 Name the routines (functions) to get the above mentioned three types of information
from the index card file as getName(), getAuthor(), and getPlayingTime() and the
routine for instructing the computer to play a song as playSong().
 It should be carefully note here that all the above mentioned four routines are concerned
with the three data items.

A.M.L. Chamini
Song
Name
Data
Author
Playingtime
getName()
getAuthor()
Routines (i.e. member function)
getPlayingTime()
playSong()

A.M.L. Chamini
• The data and the related routines are combined to together to form an

object
• Once we define a class, we can declare a group of objects for that class.

• Each object in such a group contains the data and member functions that

have been defined in that class.

• In other words, each object in such a group of objects imitates the exact

characteristics of the class, which serves as a plan or template.


A.M.L. Chamini
A Simple Java Program
(Understanding)
 File name is Hello.java
class Hello
{ public static void main(String[] args)
{ System.out.println(“Hello, Welcome to
Java Application”);} }

 As Java is a pure OOP-based language, each simple Java program is


written in the form of a class.
 In java, a class consists of certain data members and the related
A.M.L. Chamini
methods.
A Simple Java Program
(Understanding)

 Since the Hello.java program is a very simple one involving any input or
output variables, it doesn’t contain any data members.
 It contains only one method, namely the main(), which must be present
in every Java stand-alone application.
 Since this method is not expected to return any value, the return type of
this method is indicated in the above program as void.
A.M.L. Chamini
A Simple Java Program
(Understanding)

 However, in certain cases, we prefer to access the methods in a class


without creating an object for that class. Such methods are known as
static methods.
 It shall be noted here that main() is a static method.
 As is apparent from the above program, the elements of an array of
String type, called args, constitute the parameters of the main()
method.
A.M.L. Chamini
A Simple Java Program
(Understanding)

 But it is not necessary to always provide the values for these


parameters.
 The first period in System.out.println means “locate the out object in
the System class”.
 The Second period means “apply the println() method to that object”.
 The System class, the out object and the println() method have all been
predefined by the Java developers.
A.M.L. Chamini
Comments

• Comments provide information to the people who read the program


• Comments are removed by the preprocessor, therefore the compiler
ignores them
• In Java, there are two types of comments
• Single line comments//
• Delimited comments /* */ for comments with more than one line.
A.M.L. Chamini
Everything is Object Oriented

• In Java is fully object oriented, even the simplest program needs to be


written using a class.
• HelloWorld is the name of the class.
• A public class needs to be stored in a file name that matches the class
name. i.e. The above code needs to be saved in a filename called
A.M.L. Chamini

HelloWorld.java
The main method

• Java programs begin executing at method main.


The main method must be given as above.
• The main method is one of the methods in a class
• void methods do not return a value.
A.M.L. Chamini
Output Statement
System.out.println("Hello World !");

• Instructs the computer to display the data within brackets to the screen.
• “Hello World !” :String / String Literal. What you need
to display on screen
• System.out.println() moves the cursor to the next line after
displaying the data

A.M.L. Chamini
Exercise - 1
• Write a Java program to display your name and
address in 3 lines.

A.M.L. Chamini
Answer

public class FistJavaApplication {

public static void main(String[] args) {

System.out.println("Aaron Larson");
System.out.println("123 Center Ln.");
System.out.println("Plymouth, MN 33441");

A.M.L. Chamini
Printing Values
• System.out.println() and System.out.print()

A.M.L. Chamini
Variables
♥ Variable is name of reserved area allocated in memory. In
other words, it is a name of memory location.
♥ It is a combination of “vary + able” that means its value can
be changed

A.M.L. Chamini
Variables

A.M.L. Chamini
Variables - Rules
♥ The first character in a variable name should not be a digit.
♥ A variable name may consist of alphabets, digits, the
underscore character and the dollar character.
♥ A keyword should not be use as a variable name. White
spaces are not allowed within a variable name.
♥ A variable name can be of any length
A.M.L. Chamini
Variables
♥ Every variable has a data type.
♥ Every variable has a value.
♥ Every variable is the name of a storage location.
♥ Every variable has its size.

A.M.L. Chamini
Variables – Declaration
♥ Variable can declared as follows
access-specifier data-type variablename
♥ Here,
– access-specifier specifies which methods can access
the variable. Most variables are declared as private.
– data-type refers to the type of the variable. Here is a
valid type declaration statement.
A.M.L. Chamini
Variables –
Types of Variables

A.M.L. Chamini
Variables –
Types of Variables
1. Local Variable
A variable which is declared inside the method is called local variable.
2. Instance Variable
A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
3. Static variable
A variable that is declared as static is called static variable. It cannot be local.
A.M.L. Chamini
Variables –
Types of Variables
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
} //end of method.
}//end of class
A.M.L. Chamini
Data Types

A.M.L. Chamini
Data Types

int myNum = 5; // Integer (whole number)


float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
A.M.L. Chamini
Use of Variables

A.M.L. Chamini
Printing Values
• System.out.println() and System.out.print()

A.M.L. Chamini
Calculations

A.M.L. Chamini
Printing Values
• System.out.println() and System.out.print()

A.M.L. Chamini
Inputting Values from the Keyboard
• Using java.util.Scanner

A.M.L. Chamini
Classes
• A class is the abstract definition of the data type. It includes the data elements that are
part of the data type, and the operations which are defined on the data type.
• It is an Entity which could be a thing, person or something that is imaginary.

A.M.L. Chamini
Classes
• An entity can be described by the data ( Properties ) and its behavior ( methods )

A.M.L. Chamini
Classes
• Eg : Person working in a Company

Employee

EmpNo
Name
Address
BasicSalary
OtHrs OtRate
CalculateOTAmount()
CalculateNetSalary()
A.M.L. Chamini PrintPaySlip()
A.M.L. Chamini

Classes and Objects


• An Object is a specific instance of the data type (class)
• A class is a blue print of an object.
Objects
• Objects are instances of classes, which we can use to store
data and perform actions
• We need to define a class including the properties and
methods and then create as many objects which has the
same structure of the class ( House example )

A.M.L. Chamini
Class in Java
class Student {
private int studentNo;
private String name;
private int CA_mark;
private int
Final_mark;
public void assignMarks(int pCA,
int pFin) {
}
public int calculateTotal() {
}
public void printDetails() {
}
}
A.M.L. Chamini
Create a Class

To create a class, use the keyword class:

public class MyClass {


int x = 5;
}

A.M.L. Chamini
Exercise - 2
1. Create a class named as Dog. There is no need to add variables
or methods. Just create and empty class.

A.M.L. Chamini
CreatingObjects

A.M.L. Chamini
Create an Object

public class MyClass {


int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}

A.M.L. Chamini
Multiple Objects
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj1 = new MyClass(); // Object 1
MyClass myObj2 = new MyClass(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}

A.M.L. Chamini }
Exercise - 3
1. Create following objects using the Dog class. “puppy”,
“myDog” and “Timmy”

A.M.L. Chamini
Using Multiple Classes
You can also create an object of a class and access it in another class. This is
often used for better organization of classes (one class has all the attributes
and methods, while the other class holds the main() method (code to be
executed)).
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory/folder:
• MyClass.java
• OtherClass.java

A.M.L. Chamini
MyClass.java OtherClass.java

public class MyClass { class OtherClass {


int x = 5; public static void main(String[] args) {
} MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}

A.M.L. Chamini
Java Class Attributes
Create a class called "MyClass" with two attributes: x and y:

public class MyClass {


int x = 5;
int y = 3;
}

A.M.L. Chamini
Accessing Attributes

public class MyClass {


int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
A.M.L. Chamini
}
Modify Attributes
public class MyClass {
int x;

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 40;
System.out.println(myObj.x);
}
}

A.M.L. Chamini
Override existing values

public class MyClass {


int x = 10;

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}
}

A.M.L. Chamini
If you don't want the ability to override existing values, declare the attribute as final:

public class MyClass {


final int x = 10;

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 25; // will generate an error: cannot assign a value
to a final variable
System.out.println(myObj.x);
}
A.M.L. Chamini
The final keyword is useful when you want a variable
to always store the same value, like PI (3.14159...).
The final keyword is called a "modifier".

A.M.L. Chamini
Multiple Objects

public class MyClass {


int x = 5;

public static void main(String[] args) {


MyClass myObj1 = new MyClass(); // Object 1
MyClass myObj2 = new MyClass(); // Object 2
myObj2.x = 25;
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
}
A.M.L. Chamini
}
Multiple Attributes

public class Person {


String fname = "John";
String lname = "Doe";
int age = 24;

public static void main(String[] args) {


Person myObj = new Person();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);
}
A.M.L. Chamini
Exercise - 4
1. For the dog class add suitable attributes and assign values to them at the
class. In the main method create an object name as “myPuppy” and display
each attribute value using the object

A.M.L. Chamini
Java Class Methods

public class MyClass {


static void myMethod() {
System.out.println("Hello World!");
}
}

A.M.L. Chamini
Call a method inside the main method
public class MyClass {
static void myMethod() {
System.out.println("Hello World!");
}

public static void main(String[] args) {


myMethod();
}
}
A.M.L. Chamini
Static
A static method can be accessed without creating an object
of the class, unlike public, which can only be accessed by
objects:

A.M.L. Chamini
public class MyClass {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating
objects");
}

// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}

// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error

MyClass myObj = new MyClass(); // Create an object of MyClass


myObj.myPublicMethod(); // Call the public method on the object
A.M.L. Chamini
}
// Create a Car class
public class Car { Access Methods With an Object
// Create a fullThrottle() method
public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}

// Create a speed() method and add a parameter


public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}

// Inside main, call the methods on the myCar object


public static void main(String[] args) {
Car myCar = new Car(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}

// The car is going as fast as it can!


// A.M.L.
MaxChamini
speed is: 200
Call a method inside another class
public class Car {
public void fullThrottle() { class OtherClass {
System.out.println("The car is going as fast as it can!"); public static void main(String[] args) {
} Car myCar = new Car(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
public void speed(int maxSpeed) { myCar.speed(200); // Call the speed() method
System.out.println("Max speed is: " + maxSpeed); }
} }
}

A.M.L. Chamini
Exercise - 5
1. For the dog class add two methods and call these methods in the main class
using an object.

A.M.L. Chamini
Constructor
// default Constructor public static void main(String args[]) {
public Rectangle () { // default constructor called Rectangle r1
= new Rectangle();
width = 0; // Second constructor called Rectangle r2 =
length = 0; new Rectangle(10,20);
} }

// Constructor with parameters


public Rectangle (int w, int l) {
width = w;
length = l;
}
A.M.L. Chamini
Constructor
• The constructor is used to initialize the object when it is declared.
• The constructer does not return a value, and has no return type (
not even void )
• The constructors has the same name as the class.
• There can be default constructers or constructors with parameters
• When an object is declared the appropriate constructor is
A.M.L. Chamini
executed.
Constructor
 Default Constructors
public Rectangle () {
• Can be used to initialized attributes to default values width = 0;
length = 0; }

 Overloaded Constructors ( Constructors with Parameters )


• Can be used to assign values sent by the main program
as arguments
public Rectangle (int w, int l) {
width = w;
length = l;
A.M.L. Chamini }
Java Constructors

A constructor in Java is a special method that is used


to initialize objects. The constructor is called when an
object of a class is created. It can be used to set initial
values for object attributes:

A.M.L. Chamini
// Create a MyClass class
public class MyClass {
int x; // Create a class attribute

// Create a class constructor for the MyClass class


public MyClass() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {


MyClass myObj = new MyClass(); // Create an object of class MyClass (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}

// Outputs 5
A.M.L. Chamini
Note that the constructor name must match the class name,
and it cannot have a return type (like void).
Also note that the constructor is called when the object is
created.
All classes have constructors by default: if you do not create a
class constructor yourself, Java creates one for you. However,
then you are not able to set initial values for object attributes.

A.M.L. Chamini
Constructor Parameters

public class MyClass {


int x;
Constructors can also
public MyClass(int y) {
x = y; take parameters, which
} is used to initialize

public static void main(String[] args) { attributes.


MyClass myObj = new MyClass(5);
System.out.println(myObj.x);
}
}

// Outputs 5
A.M.L. Chamini
public class Car {
int modelYear;
String modelName;

public Car(int year, String name) {


modelYear = year;
modelName = name;
}

public static void main(String[] args) {


Car myCar = new Car(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}

// Outputs 1969 Mustang

A.M.L. Chamini
Exercise - 6
1. Create a constructor for the Dog class and create an object of dog class and
call one of methods of the Dog class.

A.M.L. Chamini
public static void main(String[] args) {

Dog ob1 = new Dog();


public class ConstructorEg {
ob1.Bark();
ob1.PrintDetails();
int v1, v2;
Dog ob2 = new Dog("Tutu",5);
public ConstructorEg(){
ob2.Bark();
ob2.PrintDetails();
}

public ConstructorEg(int w, int u){


// ConstructorEg ob1 = new ConstructorEg();
v1 = w;
// System.out.println(ob1.v1);
v2 = u;
// System.out.println(ob1.v2);
}
//
// ConstructorEg ob2 = new ConstructorEg(34,5);
// System.out.println(ob2.v1);
// System.out.println(ob2.v2);

A.M.L. Chamini
public class Dog {

String name;
int age;

public Dog(){

public Dog(String name1,int age1){

name = name1;
age = age1;
}
public void Bark(){
System.out.println("Baw");
}

public void PrintDetails(){


System.out.println("Name of the Dog is "+name+"Age of the Dog is
"+age);
A.M.L. Chamini
}
}
//Class Declaration
Class Dog{
//Instance Variable
String type;
String size;
int age;
String color;

//Method 1
public String getInfo(){
return(“Breed is : ”+ breed+”Size is :
”+size+”Age is : ”+age+”Color is : ”+color);
}
}
public class Execute{
public static void main (String[] args){
Dog bolognese = new Dog();
bolognese type = “Bolognese”;
bolognese size = “Small”;
bolognese age = 1;
bolognese color = “White”;

system.out.println(bolognese.getInfo());
}
}

Breed is Bolognese Size is Small Age is 1 Color is


White
Access Modifiers

For classes, you can use either public or default:

public public class MyClass {


public static void main(String[] args) {
The class is accessible by any other class System.out.println("Hello World");
}
}

A.M.L. Chamini
default

The class is only accessible by classes in the same class MyClass {


package. This is used when you don't specify a public static void main(String[] args) {
modifier. System.out.println("Hello World");
}
}

A.M.L. Chamini
For attributes, methods and constructors, you can use the one of the following:

public

The code is accessible for all classes

public class Person { class MyClass {


public String fname = "John"; public static void main(String[] args) {
public String lname = "Doe"; Person myObj = new Person();
public String email = "john@doe.com"; System.out.println("Name: " + myObj.fname + " " + myObj.lname);
public int age = 24; System.out.println("Email: " + myObj.email);
} System.out.println("Age: " + myObj.age);
}
A.M.L. Chamini }
private
The code is only accessible within the declared
public class Person { class
private String fname = "John";
private String lname = "Doe";
private String email = "john@doe.com";
private int age = 24;

public static void main(String[] args) {


Person myObj = new Person();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Email: " + myObj.email);
System.out.println("Age: " + myObj.age);
}
}
A.M.L. Chamini
class Person {
protected protected String fname = "John";
protected String lname = "Doe";
The code is accessible in the protected String email = "john@doe.com";
same package protected int age = 24;
and subclasses. }

class Student extends Person {


private int graduationYear = 2018;
public static void main(String[] args) {
Student myObj = new Student();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Email: " + myObj.email);
System.out.println("Age: " + myObj.age);
System.out.println("Graduation Year: " + myObj.graduationYear);
}
A.M.L. Chamini
}
Non-Access Modifiers

For classes, you can use either final or abstract

final

The class cannot be inherited by other classes

abstract

The class cannot be used to create objects

A.M.L. Chamini
final class Vehicle {
class MyClass {
protected String brand = "Ford";
public static void main(String[] args) {
public void honk() {
// create an object of the Student class (which
System.out.println("Tuut, tuut!");
inherits attributes and methods from Person)
}
Student myObj = new Student();
}
System.out.println("Name: " + myObj.fname + "
class Car extends Vehicle {
" + myObj.lname);
private String modelName = "Mustang";
System.out.println("Email: " + myObj.email);
public static void main(String[] args) {
System.out.println("Age: " + myObj.age);
Car myFastCar = new Car();
System.out.println("Graduation Year: " +
myFastCar.honk();
myObj.graduationYear);
System.out.println(myFastCar.brand + " " +
myObj.study(); // call abstract method
myFastCar.modelName);
}
}
}
}
A.M.L. Chamini
For attributes and methods, you can use the one of the following:

Modifier Description
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an
object
abstract Can only be used in an abstract class, and can only be used on
methods. The method does not have a body, for
example abstract void run();. The body is provided by the
subclass (inherited from).

A.M.L. Chamini
Final
public class MyClass {
final int x = 10;
final double PI = 3.14;

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 50; // will generate an error: cannot assign a value to a final variable
myObj.PI = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}

A.M.L. Chamini
Static
public class MyClass {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}

// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}

// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error

MyClass myObj = new MyClass(); // Create an object of MyClass


myObj.myPublicMethod(); // Call the public method
}
A.M.L. Chamini

}
Private & Public
• The private part of the definition specifies the data members of a class
• These are hidden from outside the class and can only be accessed though
the operations defined for the class
• The public part of the definition specifies the operations as function
prototypes
• These operations, or methods as they are called, can be accesses by the
main program.
A.M.L. Chamini
Private & Public

A.M.L. Chamini
Sample Client Program
• Write a program which will determine the square yardage to be mowed for a
rectangular yard, given the dimensions of the yard and the dimensions of the house
on that yard. It will also determine the cost of mowing the lawn which is so much
per square yard.
Yard

House

A.M.L. Chamini
Rectangle Problem

Rectangle.cpp Rectangle.java
A.M.L. Chamini
Classes and Objects
Rectangle rectangle1, rectangle2;
• This is somewhat similar to us defining simple variables. However rectangle1 and
rectangle2 are dynamic objects. Memory is allocated when you use the new command.

int marks1, marks2;

• Rectangle is an example of a class. It’s a user defined data type.


• Objects are also known as instances.

A.M.L. Chamini
Rectangle Problem

Rectangle.java
Rectangle.cpp
A.M.L. Chamini
Q & A
Ms. A.M.L. Chamini 102
Review Yourself
1. Briefly describes the errors can be seen in a program.
2. Identify the steps in the programming process.
3. Describe a real life embedded system.
References

 Programming for Engineers by Aaron R. Bradley (2011)

Ms. A.M.L. Chamini 104


Next Lecture?

Introduction to C Programming

Ms. A.M.L. Chamini 105


Thank You.

Ms. A.M.L. Chamini 106

You might also like