SlideShare uma empresa Scribd logo
1 de 19
Object Oriented
Programming
An introduction to Object Oriented
Programming concepts in Java for
absolute beginners.
Pre-requisites
• These slides aim at giving an introduction to the core
concepts of object oriented programming.
• You will need to have Java JDK installed.
• You will need to know how to compile and run Java
programs.
• The examples in these slides were compiled and
executed on a Mac running Java JDK 1.6.0_65
2
Concept 1: Classes
• A class is a blueprint of an object.
• It defines the behaviours and attributes of an object.
• Attributes, refer to the variables that can be of different
datatypes like Integer, Double, Long, String, etc.
• Behaviours, refer to the methods that are exposed by a
class.
3
Exercise 1: Create a class named “Ferrari” with
attributes Integer numberOf Wheels and behaviour
drive
• Create a directory named “oops”. We will be creating, compiling
and executing all files for the exercises within this folder.
• Create a file named Ferrari.java with the following contents.
Please do not copy/paste. Type in the code. Take a look at the
comments.
//Class name and file name should match. If you are writing a class called “Wrestler”, file should be Wrestler.java
public class Ferrari {
//Attribute
Integer numberOfWheels;
//Behaviour
public void drive(){
System.out.println("I am driving");
}
//Getter and setter
public void setNumberOfWheels(Integer numberOfWheels){this.numberOfWheels = numberOfWheels;}
public Integer getNumberOfWheels(){return this.numberOfWheels;}
}
• Compile the file using the command “javac Ferrari.java” and
make sure there are no errors.
4
Create a class “Audi” with the same attributes and behaviours as your
Ferrari class
Exercise 2
5
Concept 2: Objects
• An Object is an instantiation of a class.
• By instantiating an object, you are using the blueprint
provided by it’s class and making it usable.
• In the next example, you will be creating a class with a
main method where you will instantiate objects. The
main method is the entry point for all Java programs.
Every usable Java program, must have a main method
of the signature “public static void main(String[] args)”.
• Read more about the main method here.
6
Exercise 3: Objects
• Create a file named Main.java with the following
contents.
public class Main {
//main method
public static void main(String[] args){
//Create a new ferrari object of type Ferrari
Ferrari ferrari = new Ferrari();
//Set the attribute numberOfWheels by calling the setNumberOfWheels method
ferrari.setNumberOfWheels(4);
//Print the number of wheels by calling the getNumberOfWheels method
System.out.println(ferrari.getNumberOfWheels());
//Execute the behaviour drive by calling the drive() method
ferrari.drive();
}
}
• Compile and run the program using the commands
“javac Main.java” followed by “java Main”.
• Verify that you see the number of wheels and the text “I
am driving” printed out.
7
In the same main method as Exercise 3, instantiate an audi object of
type Audi that you created in Exercise 2.
Exercise 4
8
Concept 3: Abstraction and Inheritance
• Read the code in Ferrari.java and Audi.java. You will notice that both the
classes have the same attributes and behaviours. We are simply
rewriting the same code in both the classes.
• An Abstract class in Java, is where we declare and/or define all the
common attributes and behaviours, that can be inherited by classes that
extend the Abstract class.
• For example, both Ferrari and Audi are vehicles. All vehicles have
wheels. So, we can create an Abstract class Vehicle with attribute
numberOfWheels from which Ferrari and Audi extend and inherit the
properties.
• Confused? Take a look at the next exercise. Type in the code and
execute it instead of copy/pasting.
Exercise 5: Abstraction and Inheritance
• Create a file named Vehicle.java with the following content.
public abstract class Vehicle{
private Integer numberOfWheels;
public void setNumberOfWheels(Integer numberOfWheels){
this.numberOfWheels = numberOfWheels;
}
public Integer getNumberOfWheels(){
return this.numberOfWheels;
}
}
• Remove the attribute numberOfWheels and the getNumberOfWheels and setNumberOfWheels
methods from Ferrari class and Audi class. Update the class to extend Vehicle class.
public class Ferrari extends Vehicle{
//Behaviour
public void drive(){
System.out.println("I am driving");
}
}
• Compile the new classes using the command “javac Vehicle.java Ferrari.java Audi.java Main.java”
• Run the program using the command “java Main”. You will see that even though Ferrari and Audi
do not have the attribute numberOfWheels, it is inheriting it from the Vehicle abstract class. This
resulted in lesser lines of code. And in large Java programs, helps in easier maintainability of the
application, and enables easier extension of the applications. For example, if I want all vehicles to
have a new property numberOfSeats, instead of adding the attribute in each class, I can add the
attribute to the abstract class and all the classes extending this class inherit the new attribute.
1. Move the behaviour drive() to the abstract class and remove the
behaviour from Ferrari and Audi classes.
2. Create an abstract class LivingBeing with attribute numberOfLegs
and it’s getter and setter methods. Create two classes Dog and
Man. Create a Main class with a main method. Instantiate a new
Dog and Man object. Set the number of legs and print the number
of legs.
Exercise 6
Concept 4: Interfaces
• An interface can be thought of a class that declares a
contract. All classes that implement an interface, must and
should provide a definition for the methods declared in the
interface.
• Let us take an example. A bird, and an aircraft, the entities
are not related to one another. But both have a common
behaviour. Both birds and aircrafts, fly. Birds and aircrafts are
flyable.
• Thinking in terms of interfaces, if we want to create a bird or
an aircraft, both should be flyable.
• Take a look at the next exercise.
Exercise 7: Inheritance
• Create a class Aircraft and another class Bird. We have already
identified that all birds and aircrafts, must be flyable. Therefore, we
can create an interface Flyable which both Aircraft and Bird can
implement. By implementing an interface, we are setting a contract
saying all birds and aircrafts must fly by providing a definition for
the fly method declared in the interface Flyable.
public interface Flyable{
public void fly(Integer altitude);
}
public class Aircraft implements Flyable{
public void fly(Integer altitude){
System.out.println("Aircraft in flight. Current altitude " + altitude);
}
}
public class Bird implements Flyable{
public void fly(Integer altitude){
System.out.println("Bird in flight. Current altitude " + altitude);
}
}
public class Main {
public static void main(String[] args){
Bird bird = new Bird();
bird.fly(400);
Aircraft aircraft = new Aircraft();
aircraft.fly(5000);
}
}
Try: What happens when you remove the fly method from Bird class?
Create an interface Printable with print() method. Create two classes
DesktopPrinter() and LaserPrinter() that implement Printable method.
Exercise 8
Concept 5: Polymorphism and why use
interfaces?
• Looking at the examples, the first question we ask is why do we even need an interface?
• One of the main uses of interfaces, is to exercise the concept of polymorphism. Polymorphism,
simply means many forms.
• Take a look at the example below. We have used an ArrayList to add two completely unrelated
objects. Bird and Aircraft have nothing in common but both implement Printable.
public interface Printable{
public void print();
}
public class DesktopPrinter implements Printable{
public void print(){
System.out.println("Printing from a desktop printer");
}
}
public class LaserPrinter implements Printable{
public void print(){
System.out.println("Printing from a laser printer");
}
}
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
DesktopPrinter desktopPrinter = new DesktopPrinter();
LaserPrinter laserPrinter = new LaserPrinter();
ArrayList<Printable> printableObjects = new ArrayList<Printable>();
printableObjects.add(desktopPrinter);
printableObjects.add(laserPrinter);
for(Printable object:printableObjects){
object.print();
}
}
}
Concept 6: Over-riding and Over-loading
• Over-riding: When you extend a class, the extending
class can provide it’s own implementation of a method.
This is called method over-riding.
• Over-loading: Having two methods with the same name
but different parameters is known as Over-loading.
Exercise 9: Over-riding
• Abstract class vehicle has a method named drive(). We can over-ride this method in class Ferrari to print more specific
information. Modify the code as below.
public abstract class Vehicle{
private Integer numberOfWheels;
public void setNumberOfWheels(Integer numberOfWheels){
this.numberOfWheels = numberOfWheels;
}
public Integer getNumberOfWheels(){
return this.numberOfWheels;
}
//Behaviour
public void drive(){
System.out.println("I am driving");
}
}
public class Ferrari extends Vehicle{
//Over-riding the method
public void drive(){
System.out.println("I am driving a Ferrari.");
}
}
public class Audi extends Vehicle{}
public class Main {
//main method
public static void main(String[] args){
//Create a new ferrari object of type Ferrari
Ferrari ferrari = new Ferrari();
//Set the attribute numberOfWheels by calling the setNumberOfWheels method
ferrari.setNumberOfWheels(4);
//Print the number of wheels by calling the getNumberOfWheels method
System.out.println(ferrari.getNumberOfWheels());
//Execute the behaviour drive by calling the drive() method
ferrari.drive();
Audi audi = new Audi();
audi.drive();
}
}
• Compile the above code and run it. Notice how, Ferrari prints more specific information “I am driving a Ferrari” and Audi still
prints the “I am driving” message. This is because the method drive() is over-ridden in Ferrari class.
Exercise 10: Over-loading
• Modify the code for class Ferrari and the main method as provided
below.
public class Ferrari extends Vehicle{
//Overridden method
public void drive(){
System.out.println("I am driving a Ferrari.");
}
//Overloaded method
public void drive(Integer milesPerHour){
System.out.println("I am driving a Ferrari at " + milesPerHour + " miles per hour");
}
}
public class Main {
//main method
public static void main(String[] args){
//Create a new ferrari object of type Ferrari
Ferrari ferrari = new Ferrari();
//Set the attribute numberOfWheels by calling the setNumberOfWheels method
ferrari.setNumberOfWheels(4);
//Print the number of wheels by calling the getNumberOfWheels method
System.out.println(ferrari.getNumberOfWheels());
//Execute the behaviour drive by calling the drive() method
ferrari.drive();
ferrari.drive(80);
}
}
• Notice how class Ferrari has two methods with the same name
drive.
Concept 7: Encapsulation
• Encapsulation is the concept of hiding data and
restricting access to attributes and behaviour.
• There are 4 levels of access in Java.
1. default: access limited to classes within the same package
2. public: access available to all other classes
3. private: access available only within the same class
4. protected: access available to classes within the same package and
subclasses

Mais conteúdo relacionado

Mais procurados

Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentalsjavaease
 
Data abstraction and object orientation
Data abstraction and object orientationData abstraction and object orientation
Data abstraction and object orientationHoang Nguyen
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPTAjay Chimmani
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaGlenn Guden
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programmingNeelesh Shukla
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Sakthi Durai
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)indiangarg
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]Rome468
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languagesppd1961
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oopcolleges
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Uzair Salman
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Objectdkpawar
 

Mais procurados (20)

Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
 
Data abstraction and object orientation
Data abstraction and object orientationData abstraction and object orientation
Data abstraction and object orientation
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Oop java
Oop javaOop java
Oop java
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
 
Oops in java
Oops in javaOops in java
Oops in java
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
 

Destaque

Object-Oriented Programming Concepts
Object-Oriented Programming ConceptsObject-Oriented Programming Concepts
Object-Oriented Programming ConceptsKwangshin Oh
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming ConceptsAbhigyan Singh Yadav
 
Object Oriented Software Engineering
Object Oriented Software EngineeringObject Oriented Software Engineering
Object Oriented Software EngineeringAli Haider
 
Object oriented programming concept
Object oriented programming conceptObject oriented programming concept
Object oriented programming conceptPina Parmar
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01Adil Kakakhel
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programmingSachin Sharma
 
Bus tracking application in Android
Bus tracking application in AndroidBus tracking application in Android
Bus tracking application in Androidyashonil
 
Online recruitment system
Online recruitment systemOnline recruitment system
Online recruitment systemKomal Singh
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering conceptsKomal Singh
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 

Destaque (11)

Object-Oriented Programming Concepts
Object-Oriented Programming ConceptsObject-Oriented Programming Concepts
Object-Oriented Programming Concepts
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Object Oriented Software Engineering
Object Oriented Software EngineeringObject Oriented Software Engineering
Object Oriented Software Engineering
 
Object oriented programming concept
Object oriented programming conceptObject oriented programming concept
Object oriented programming concept
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Bus tracking application in Android
Bus tracking application in AndroidBus tracking application in Android
Bus tracking application in Android
 
Online recruitment system
Online recruitment systemOnline recruitment system
Online recruitment system
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering concepts
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 

Semelhante a Object Oriented Programming Concepts

Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT studentsPartnered Health
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to JavaSMIJava
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.pptrani marri
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldYakov Fain
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Unit2 java
Unit2 javaUnit2 java
Unit2 javamrecedu
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery PluginRavi Mone
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptxarjun431527
 

Semelhante a Object Oriented Programming Concepts (20)

Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Java Intro: Unit1. Hello World
Java Intro: Unit1. Hello WorldJava Intro: Unit1. Hello World
Java Intro: Unit1. Hello World
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Android programming-basics
Android programming-basicsAndroid programming-basics
Android programming-basics
 
Unit2 java
Unit2 javaUnit2 java
Unit2 java
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 
Class 1 blog
Class 1 blogClass 1 blog
Class 1 blog
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 

Último

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Último (20)

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Object Oriented Programming Concepts

  • 1. Object Oriented Programming An introduction to Object Oriented Programming concepts in Java for absolute beginners.
  • 2. Pre-requisites • These slides aim at giving an introduction to the core concepts of object oriented programming. • You will need to have Java JDK installed. • You will need to know how to compile and run Java programs. • The examples in these slides were compiled and executed on a Mac running Java JDK 1.6.0_65 2
  • 3. Concept 1: Classes • A class is a blueprint of an object. • It defines the behaviours and attributes of an object. • Attributes, refer to the variables that can be of different datatypes like Integer, Double, Long, String, etc. • Behaviours, refer to the methods that are exposed by a class. 3
  • 4. Exercise 1: Create a class named “Ferrari” with attributes Integer numberOf Wheels and behaviour drive • Create a directory named “oops”. We will be creating, compiling and executing all files for the exercises within this folder. • Create a file named Ferrari.java with the following contents. Please do not copy/paste. Type in the code. Take a look at the comments. //Class name and file name should match. If you are writing a class called “Wrestler”, file should be Wrestler.java public class Ferrari { //Attribute Integer numberOfWheels; //Behaviour public void drive(){ System.out.println("I am driving"); } //Getter and setter public void setNumberOfWheels(Integer numberOfWheels){this.numberOfWheels = numberOfWheels;} public Integer getNumberOfWheels(){return this.numberOfWheels;} } • Compile the file using the command “javac Ferrari.java” and make sure there are no errors. 4
  • 5. Create a class “Audi” with the same attributes and behaviours as your Ferrari class Exercise 2 5
  • 6. Concept 2: Objects • An Object is an instantiation of a class. • By instantiating an object, you are using the blueprint provided by it’s class and making it usable. • In the next example, you will be creating a class with a main method where you will instantiate objects. The main method is the entry point for all Java programs. Every usable Java program, must have a main method of the signature “public static void main(String[] args)”. • Read more about the main method here. 6
  • 7. Exercise 3: Objects • Create a file named Main.java with the following contents. public class Main { //main method public static void main(String[] args){ //Create a new ferrari object of type Ferrari Ferrari ferrari = new Ferrari(); //Set the attribute numberOfWheels by calling the setNumberOfWheels method ferrari.setNumberOfWheels(4); //Print the number of wheels by calling the getNumberOfWheels method System.out.println(ferrari.getNumberOfWheels()); //Execute the behaviour drive by calling the drive() method ferrari.drive(); } } • Compile and run the program using the commands “javac Main.java” followed by “java Main”. • Verify that you see the number of wheels and the text “I am driving” printed out. 7
  • 8. In the same main method as Exercise 3, instantiate an audi object of type Audi that you created in Exercise 2. Exercise 4 8
  • 9. Concept 3: Abstraction and Inheritance • Read the code in Ferrari.java and Audi.java. You will notice that both the classes have the same attributes and behaviours. We are simply rewriting the same code in both the classes. • An Abstract class in Java, is where we declare and/or define all the common attributes and behaviours, that can be inherited by classes that extend the Abstract class. • For example, both Ferrari and Audi are vehicles. All vehicles have wheels. So, we can create an Abstract class Vehicle with attribute numberOfWheels from which Ferrari and Audi extend and inherit the properties. • Confused? Take a look at the next exercise. Type in the code and execute it instead of copy/pasting.
  • 10. Exercise 5: Abstraction and Inheritance • Create a file named Vehicle.java with the following content. public abstract class Vehicle{ private Integer numberOfWheels; public void setNumberOfWheels(Integer numberOfWheels){ this.numberOfWheels = numberOfWheels; } public Integer getNumberOfWheels(){ return this.numberOfWheels; } } • Remove the attribute numberOfWheels and the getNumberOfWheels and setNumberOfWheels methods from Ferrari class and Audi class. Update the class to extend Vehicle class. public class Ferrari extends Vehicle{ //Behaviour public void drive(){ System.out.println("I am driving"); } } • Compile the new classes using the command “javac Vehicle.java Ferrari.java Audi.java Main.java” • Run the program using the command “java Main”. You will see that even though Ferrari and Audi do not have the attribute numberOfWheels, it is inheriting it from the Vehicle abstract class. This resulted in lesser lines of code. And in large Java programs, helps in easier maintainability of the application, and enables easier extension of the applications. For example, if I want all vehicles to have a new property numberOfSeats, instead of adding the attribute in each class, I can add the attribute to the abstract class and all the classes extending this class inherit the new attribute.
  • 11. 1. Move the behaviour drive() to the abstract class and remove the behaviour from Ferrari and Audi classes. 2. Create an abstract class LivingBeing with attribute numberOfLegs and it’s getter and setter methods. Create two classes Dog and Man. Create a Main class with a main method. Instantiate a new Dog and Man object. Set the number of legs and print the number of legs. Exercise 6
  • 12. Concept 4: Interfaces • An interface can be thought of a class that declares a contract. All classes that implement an interface, must and should provide a definition for the methods declared in the interface. • Let us take an example. A bird, and an aircraft, the entities are not related to one another. But both have a common behaviour. Both birds and aircrafts, fly. Birds and aircrafts are flyable. • Thinking in terms of interfaces, if we want to create a bird or an aircraft, both should be flyable. • Take a look at the next exercise.
  • 13. Exercise 7: Inheritance • Create a class Aircraft and another class Bird. We have already identified that all birds and aircrafts, must be flyable. Therefore, we can create an interface Flyable which both Aircraft and Bird can implement. By implementing an interface, we are setting a contract saying all birds and aircrafts must fly by providing a definition for the fly method declared in the interface Flyable. public interface Flyable{ public void fly(Integer altitude); } public class Aircraft implements Flyable{ public void fly(Integer altitude){ System.out.println("Aircraft in flight. Current altitude " + altitude); } } public class Bird implements Flyable{ public void fly(Integer altitude){ System.out.println("Bird in flight. Current altitude " + altitude); } } public class Main { public static void main(String[] args){ Bird bird = new Bird(); bird.fly(400); Aircraft aircraft = new Aircraft(); aircraft.fly(5000); } } Try: What happens when you remove the fly method from Bird class?
  • 14. Create an interface Printable with print() method. Create two classes DesktopPrinter() and LaserPrinter() that implement Printable method. Exercise 8
  • 15. Concept 5: Polymorphism and why use interfaces? • Looking at the examples, the first question we ask is why do we even need an interface? • One of the main uses of interfaces, is to exercise the concept of polymorphism. Polymorphism, simply means many forms. • Take a look at the example below. We have used an ArrayList to add two completely unrelated objects. Bird and Aircraft have nothing in common but both implement Printable. public interface Printable{ public void print(); } public class DesktopPrinter implements Printable{ public void print(){ System.out.println("Printing from a desktop printer"); } } public class LaserPrinter implements Printable{ public void print(){ System.out.println("Printing from a laser printer"); } } import java.util.ArrayList; public class Main { public static void main(String[] args){ DesktopPrinter desktopPrinter = new DesktopPrinter(); LaserPrinter laserPrinter = new LaserPrinter(); ArrayList<Printable> printableObjects = new ArrayList<Printable>(); printableObjects.add(desktopPrinter); printableObjects.add(laserPrinter); for(Printable object:printableObjects){ object.print(); } } }
  • 16. Concept 6: Over-riding and Over-loading • Over-riding: When you extend a class, the extending class can provide it’s own implementation of a method. This is called method over-riding. • Over-loading: Having two methods with the same name but different parameters is known as Over-loading.
  • 17. Exercise 9: Over-riding • Abstract class vehicle has a method named drive(). We can over-ride this method in class Ferrari to print more specific information. Modify the code as below. public abstract class Vehicle{ private Integer numberOfWheels; public void setNumberOfWheels(Integer numberOfWheels){ this.numberOfWheels = numberOfWheels; } public Integer getNumberOfWheels(){ return this.numberOfWheels; } //Behaviour public void drive(){ System.out.println("I am driving"); } } public class Ferrari extends Vehicle{ //Over-riding the method public void drive(){ System.out.println("I am driving a Ferrari."); } } public class Audi extends Vehicle{} public class Main { //main method public static void main(String[] args){ //Create a new ferrari object of type Ferrari Ferrari ferrari = new Ferrari(); //Set the attribute numberOfWheels by calling the setNumberOfWheels method ferrari.setNumberOfWheels(4); //Print the number of wheels by calling the getNumberOfWheels method System.out.println(ferrari.getNumberOfWheels()); //Execute the behaviour drive by calling the drive() method ferrari.drive(); Audi audi = new Audi(); audi.drive(); } } • Compile the above code and run it. Notice how, Ferrari prints more specific information “I am driving a Ferrari” and Audi still prints the “I am driving” message. This is because the method drive() is over-ridden in Ferrari class.
  • 18. Exercise 10: Over-loading • Modify the code for class Ferrari and the main method as provided below. public class Ferrari extends Vehicle{ //Overridden method public void drive(){ System.out.println("I am driving a Ferrari."); } //Overloaded method public void drive(Integer milesPerHour){ System.out.println("I am driving a Ferrari at " + milesPerHour + " miles per hour"); } } public class Main { //main method public static void main(String[] args){ //Create a new ferrari object of type Ferrari Ferrari ferrari = new Ferrari(); //Set the attribute numberOfWheels by calling the setNumberOfWheels method ferrari.setNumberOfWheels(4); //Print the number of wheels by calling the getNumberOfWheels method System.out.println(ferrari.getNumberOfWheels()); //Execute the behaviour drive by calling the drive() method ferrari.drive(); ferrari.drive(80); } } • Notice how class Ferrari has two methods with the same name drive.
  • 19. Concept 7: Encapsulation • Encapsulation is the concept of hiding data and restricting access to attributes and behaviour. • There are 4 levels of access in Java. 1. default: access limited to classes within the same package 2. public: access available to all other classes 3. private: access available only within the same class 4. protected: access available to classes within the same package and subclasses