SlideShare a Scribd company logo
Java 102: Intro to Object-oriented
Programming with Java
Java 102
• Object-oriented Programming
– Fundamentals
• Classes & Objects
• Methods & Constructors
• Encapsulation
• Inheritance
– Libraries & Clients
Java 102: Intro to Object-
oriented Programming with Java
Fundamentals
Classes
• Java is an object-oriented language
• Its constructs represent concepts from the
real world.
• Each Java program has at least one class that
knows how to do certain actions or has
properties
• Classes in Java may have methods and
properties (a.k.a. attributes or fields)
Example 1: Car Class
Objects
• Objects are created using Classes as a
blueprint
• Each object is an instance of a Class
• Objects must be instantiated before they can
be accessed or used in a program
• Objects are instantiated using the new
keyword
Example 2: Creating Car Objects
• These two Car instances are created with the
new operator:
Car car1 = new Car();
Car car2 = new Car();
• Now the variables car1 and car2 represent
new instances of Car:
car1.color=“blue”;
car2.color=“red”;!
Encapsulation
public class Car {
private String make;
private String model;
private String color;
public void setColor(String color){
this.color = color;
}
public String getColor(){
return this.color;
}
void startEngine(){
System.out.println("starting
engine");
}
void stopEngine(){
System.out.println("stopping
engine");
}
variables store the state of the objects that
are created from this class. Ideally. these
should not be accessed directly by other
objects
getters and setters encapsulation the state
of objects. All access to object variables
should be done through this mechanism
Methods encapsulate the behavior of
objects created from this class
Packages
• Packages are used for grouping classes within
a java project
• Packages provide a way to organise code into
cohesive groups
• They are just folders on the filesystem
• IDE’s replace the slashes with a dot as part of
convention
Hands-on Exercise
Creating Objects
Functions
• A sequence of program instructions that perform
a specific task that are packaged as a unit
• Takes zero or more input arguments.
• Returns one output value.
• May have side effects
• Examples
– Scientists use mathematical functions to calculate
formulas.
– Programmers use functions to build modular
programs.
Methods
• Two types…
– Class Level Methods
– Object/instance level methods
• Class level methods are referred to as static methods
• Method declaration referred to as the signature
– Method name
– Parameter types
• Examples.
– Built-in static methods: Math.random(), Math.abs(),
Integer.parseInt().
– I/O libraries: System.out.print(),
– User-defined methods: main(), etc
Benefits of Methods?
• Methods enable you to build a new layer of
abstraction.
– Takes you beyond pre-packaged libraries.
– You build the functionality you need
• Process.
– Step 1: identify a useful feature
– Step 2: implement it
– Step 3: use it (re-use it in any of your programs).
Anatomy of a Java Method
Scope
• The block of code that can refer to that named variable
• E.g. A variable's scope is code following in the block.
• Best practice: declare variables to limit their scope
Hands-on Exercise
Working with Methods
Constructors
• Constructors are special methods
• They are called only once when the class is being instantiated:
Tax t = new Tax(40000, “CA”,4);
• They must have the same name as the class.
• They can’t return a value and you don’t use void as a return type.
public class Tax {
// class variables / fields
private double grossIncome;
private String state;
private int dependents;
// Constructor
public Tax (double grossIncome, String state, int depen){
// class variable initialization
this.grossIncome = grossIncome;
this.state = state;
this.dependents = dependents;
}
}
Method Overloading
• Method overloading means having a class with more
than one method having the same name but
different argument lists.
class LoanShark{
int calcLoanPayment(int amount, int numberOfMonths){
// by default, calculate for New York state
calcLoanPayment(amount, numberOfMonths, “NY”);
}
int calcLoanPayment(int amount, int numberOfMonths, String state){
// Your code for calculating loan payments goes here
}
}
Hands-on Exercise
Method Overloading
Inheritance
• Ability to define a new class based on an existing one.
• E.g. lets create a James Bond Car from our existing Car class
Class Inheritance
<<abstract>>
Person
Employee Contractor
extends
Method Overriding
• If a subclass has the method with the same name
and argument list, it will override (suppress) the
corresponding method of its ancestor.
• Method overriding comes handy in the following
situations:
• The source code of the super class is not
available, but you still need to change its
functionality
• The original version of the method is still valid in
some cases, and you want to keep it as is
Hands-on Exercise
Inheritance
Classes and Objects Summary
• A class declaration names the class and encloses the class body between
braces
• The class name can be preceded by modifiers e.g. public, private
• The class body contains fields, methods, and constructors
• A class uses fields to contain state information and uses methods to
implement behaviour
• Constructors that initialize a new instance of a class share its name and
look like methods without a return type
• Specify a class variable or a class method by using the static keyword in
the member's declaration
• Class variables are shared by all instances of a class and can be accessed
through the class name as well as an instance reference
• You create an object from a class by using the new operator and a
constructor
• The garbage collector automatically cleans up unused objects
Java 102: Intro to Object-oriented
Programming with Java
Java Libraries
Definitions
• Library - a module whose methods are
primarily intended for use by many other
programs.
• Client - a program that calls a library.
• API - the contract between client and
implementation.
• Implementation - a program that implements
the methods in an API.
Example: Standard Random
• A library to generate pseudo-random numbers.
Source: http://search.dilbert.com/comic/Tour%20Of%20Accounting
Standard Random API
Standard Random Implementation
public class StdRandom {
//between 0 and N-1
public static int uniform (int N){
return (int)(Math.random() * N);
}
// between lo and hi
public static double uniform (double lo, double hi){
return lo + (int)(Math.random() * (hi-lo));
}
// truth with probability
public static boolean bernoulli(double p){
return Math.random() < p;
}
}
Hands-on Exercise
Using a Java Library
Java Libraries Summary
• Why use libraries?
– Makes code easier to understand.
– Makes code easier to debug.
– Makes code easier to maintain and improve.
– Makes code easier to reuse.
Homework Exercise
• Invent and program any sample application to
illustrate inheritance.
• For example, think of the classes Cat and Dog,
Man and Woman, or a store inventory that
has to be discounted...
Further Reading
• OO Concepts - http://docs.oracle.com/javase/tutorial/java/concepts/index.html
• Classes and Objects – http://docs.oracle.com/javase/tutorial/java/javaOO/index.html
• Interfaces and Inheritance - http://docs.oracle.com/javase/tutorial/java/IandI/index.html
• Tools, tips and tricks for Unit Testing Java applications - http://www.junit.org

More Related Content

What's hot (14)

PPTX
Core java
Shivaraj R
 
PPT
Object Oriented Programming with Java
backdoor
 
PPTX
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Sagar Verma
 
PPT
Object Oriented Programming with Java
Jussi Pohjolainen
 
PPT
Core java
kasaragaddaslide
 
PPT
Java Tutorial
Singsys Pte Ltd
 
PPTX
Object oriented programming-with_java
Hoang Nguyen
 
PPTX
6. static keyword
Indu Sharma Bhardwaj
 
PPSX
Core java lessons
vivek shah
 
PPTX
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PPTX
Scala basic
Nguyen Tuan
 
PDF
Core Java Tutorial
eMexo Technologies
 
Core java
Shivaraj R
 
Object Oriented Programming with Java
backdoor
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Sagar Verma
 
Object Oriented Programming with Java
Jussi Pohjolainen
 
Core java
kasaragaddaslide
 
Java Tutorial
Singsys Pte Ltd
 
Object oriented programming-with_java
Hoang Nguyen
 
6. static keyword
Indu Sharma Bhardwaj
 
Core java lessons
vivek shah
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Core java complete ppt(note)
arvind pandey
 
Scala basic
Nguyen Tuan
 
Core Java Tutorial
eMexo Technologies
 

Viewers also liked (20)

PDF
Introduction to Agile
agorolabs
 
PPTX
Computer Programming Overview
agorolabs
 
PPTX
Java 103 intro to java data structures
agorolabs
 
PPTX
oops concept in java | object oriented programming in java
CPD INDIA
 
PPTX
How to Initiate Kids Into Java Programming
Felix Roberge
 
PDF
Java kid8x11
Davidson Gilbert
 
PPT
Introduction to Java Programming Language
Karwan Mustafa Kareem
 
PDF
Java threading
Chinh Ngo Nguyen
 
ODP
Drupal Camp Kiev 2012 - High Performance Drupal Web Sites
Jean-Baptiste Guerraz
 
PPTX
Java basic
Pooja Thakur
 
PDF
CON 3431 - Introducing Java Programming to Kids
Arun Gupta
 
PPSX
Edp111c z2-001
Jake Branden Dy
 
PDF
Csc1401 lecture07 -external memory
IIUM
 
PDF
It Is Possible to Do Object-Oriented Programming in Java
Kevlin Henney
 
PDF
Enum Report
enumplatform
 
PDF
Java Day-2
People Strategists
 
PDF
Java Day-7
People Strategists
 
PPTX
Data structures and algorithms lab5
Bianca Teşilă
 
PPSX
data structure(tree operations)
Waheed Khalid
 
PDF
Java data structures for principled programmer
spnr15z
 
Introduction to Agile
agorolabs
 
Computer Programming Overview
agorolabs
 
Java 103 intro to java data structures
agorolabs
 
oops concept in java | object oriented programming in java
CPD INDIA
 
How to Initiate Kids Into Java Programming
Felix Roberge
 
Java kid8x11
Davidson Gilbert
 
Introduction to Java Programming Language
Karwan Mustafa Kareem
 
Java threading
Chinh Ngo Nguyen
 
Drupal Camp Kiev 2012 - High Performance Drupal Web Sites
Jean-Baptiste Guerraz
 
Java basic
Pooja Thakur
 
CON 3431 - Introducing Java Programming to Kids
Arun Gupta
 
Edp111c z2-001
Jake Branden Dy
 
Csc1401 lecture07 -external memory
IIUM
 
It Is Possible to Do Object-Oriented Programming in Java
Kevlin Henney
 
Enum Report
enumplatform
 
Java Day-2
People Strategists
 
Java Day-7
People Strategists
 
Data structures and algorithms lab5
Bianca Teşilă
 
data structure(tree operations)
Waheed Khalid
 
Java data structures for principled programmer
spnr15z
 
Ad

Similar to Java 102 intro to object-oriented programming in java (20)

PDF
CS8392-OOPS-Printed-Notes-All-Units.pdf for students
KaviShetty
 
PPT
Md02 - Getting Started part-2
Rakesh Madugula
 
PPTX
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
PDF
Introduction to Java Object Oiented Concepts and Basic terminologies
TabassumMaktum
 
PPTX
Android Training (Java Review)
Khaled Anaqwa
 
PPTX
The smartpath information systems java
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
PPTX
OOP in Java Presentation.pptx
mrxyz19
 
PDF
JAVA-PPT'S.pdf
AnmolVerma363503
 
PPTX
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
PPTX
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
 
PPTX
java part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
PDF
Programming Laboratory Unit 1.pdf
swapnilslide2019
 
PPTX
Java 102
Manuela Grindei
 
PPTX
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
PPTX
JAVA-PPT'S.pptx
RaazIndia
 
ODP
Synapseindia reviews.odp.
Tarunsingh198
 
PDF
Java/J2EE interview Qestions
Arun Vasanth
 
PPT
Java tutorials
saryu2011
 
PPT
core java
Vinodh Kumar
 
CS8392-OOPS-Printed-Notes-All-Units.pdf for students
KaviShetty
 
Md02 - Getting Started part-2
Rakesh Madugula
 
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
Introduction to Java Object Oiented Concepts and Basic terminologies
TabassumMaktum
 
Android Training (Java Review)
Khaled Anaqwa
 
The smartpath information systems java
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
OOP in Java Presentation.pptx
mrxyz19
 
JAVA-PPT'S.pdf
AnmolVerma363503
 
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
 
java part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Programming Laboratory Unit 1.pdf
swapnilslide2019
 
Java 102
Manuela Grindei
 
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
JAVA-PPT'S.pptx
RaazIndia
 
Synapseindia reviews.odp.
Tarunsingh198
 
Java/J2EE interview Qestions
Arun Vasanth
 
Java tutorials
saryu2011
 
core java
Vinodh Kumar
 
Ad

Recently uploaded (20)

PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
Tally software_Introduction_Presentation
AditiBansal54083
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 

Java 102 intro to object-oriented programming in java

  • 1. Java 102: Intro to Object-oriented Programming with Java
  • 2. Java 102 • Object-oriented Programming – Fundamentals • Classes & Objects • Methods & Constructors • Encapsulation • Inheritance – Libraries & Clients
  • 3. Java 102: Intro to Object- oriented Programming with Java Fundamentals
  • 4. Classes • Java is an object-oriented language • Its constructs represent concepts from the real world. • Each Java program has at least one class that knows how to do certain actions or has properties • Classes in Java may have methods and properties (a.k.a. attributes or fields)
  • 6. Objects • Objects are created using Classes as a blueprint • Each object is an instance of a Class • Objects must be instantiated before they can be accessed or used in a program • Objects are instantiated using the new keyword
  • 7. Example 2: Creating Car Objects • These two Car instances are created with the new operator: Car car1 = new Car(); Car car2 = new Car(); • Now the variables car1 and car2 represent new instances of Car: car1.color=“blue”; car2.color=“red”;!
  • 8. Encapsulation public class Car { private String make; private String model; private String color; public void setColor(String color){ this.color = color; } public String getColor(){ return this.color; } void startEngine(){ System.out.println("starting engine"); } void stopEngine(){ System.out.println("stopping engine"); } variables store the state of the objects that are created from this class. Ideally. these should not be accessed directly by other objects getters and setters encapsulation the state of objects. All access to object variables should be done through this mechanism Methods encapsulate the behavior of objects created from this class
  • 9. Packages • Packages are used for grouping classes within a java project • Packages provide a way to organise code into cohesive groups • They are just folders on the filesystem • IDE’s replace the slashes with a dot as part of convention
  • 11. Functions • A sequence of program instructions that perform a specific task that are packaged as a unit • Takes zero or more input arguments. • Returns one output value. • May have side effects • Examples – Scientists use mathematical functions to calculate formulas. – Programmers use functions to build modular programs.
  • 12. Methods • Two types… – Class Level Methods – Object/instance level methods • Class level methods are referred to as static methods • Method declaration referred to as the signature – Method name – Parameter types • Examples. – Built-in static methods: Math.random(), Math.abs(), Integer.parseInt(). – I/O libraries: System.out.print(), – User-defined methods: main(), etc
  • 13. Benefits of Methods? • Methods enable you to build a new layer of abstraction. – Takes you beyond pre-packaged libraries. – You build the functionality you need • Process. – Step 1: identify a useful feature – Step 2: implement it – Step 3: use it (re-use it in any of your programs).
  • 14. Anatomy of a Java Method
  • 15. Scope • The block of code that can refer to that named variable • E.g. A variable's scope is code following in the block. • Best practice: declare variables to limit their scope
  • 17. Constructors • Constructors are special methods • They are called only once when the class is being instantiated: Tax t = new Tax(40000, “CA”,4); • They must have the same name as the class. • They can’t return a value and you don’t use void as a return type. public class Tax { // class variables / fields private double grossIncome; private String state; private int dependents; // Constructor public Tax (double grossIncome, String state, int depen){ // class variable initialization this.grossIncome = grossIncome; this.state = state; this.dependents = dependents; } }
  • 18. Method Overloading • Method overloading means having a class with more than one method having the same name but different argument lists. class LoanShark{ int calcLoanPayment(int amount, int numberOfMonths){ // by default, calculate for New York state calcLoanPayment(amount, numberOfMonths, “NY”); } int calcLoanPayment(int amount, int numberOfMonths, String state){ // Your code for calculating loan payments goes here } }
  • 20. Inheritance • Ability to define a new class based on an existing one. • E.g. lets create a James Bond Car from our existing Car class
  • 22. Method Overriding • If a subclass has the method with the same name and argument list, it will override (suppress) the corresponding method of its ancestor. • Method overriding comes handy in the following situations: • The source code of the super class is not available, but you still need to change its functionality • The original version of the method is still valid in some cases, and you want to keep it as is
  • 24. Classes and Objects Summary • A class declaration names the class and encloses the class body between braces • The class name can be preceded by modifiers e.g. public, private • The class body contains fields, methods, and constructors • A class uses fields to contain state information and uses methods to implement behaviour • Constructors that initialize a new instance of a class share its name and look like methods without a return type • Specify a class variable or a class method by using the static keyword in the member's declaration • Class variables are shared by all instances of a class and can be accessed through the class name as well as an instance reference • You create an object from a class by using the new operator and a constructor • The garbage collector automatically cleans up unused objects
  • 25. Java 102: Intro to Object-oriented Programming with Java Java Libraries
  • 26. Definitions • Library - a module whose methods are primarily intended for use by many other programs. • Client - a program that calls a library. • API - the contract between client and implementation. • Implementation - a program that implements the methods in an API.
  • 27. Example: Standard Random • A library to generate pseudo-random numbers. Source: http://search.dilbert.com/comic/Tour%20Of%20Accounting
  • 29. Standard Random Implementation public class StdRandom { //between 0 and N-1 public static int uniform (int N){ return (int)(Math.random() * N); } // between lo and hi public static double uniform (double lo, double hi){ return lo + (int)(Math.random() * (hi-lo)); } // truth with probability public static boolean bernoulli(double p){ return Math.random() < p; } }
  • 31. Java Libraries Summary • Why use libraries? – Makes code easier to understand. – Makes code easier to debug. – Makes code easier to maintain and improve. – Makes code easier to reuse.
  • 32. Homework Exercise • Invent and program any sample application to illustrate inheritance. • For example, think of the classes Cat and Dog, Man and Woman, or a store inventory that has to be discounted...
  • 33. Further Reading • OO Concepts - http://docs.oracle.com/javase/tutorial/java/concepts/index.html • Classes and Objects – http://docs.oracle.com/javase/tutorial/java/javaOO/index.html • Interfaces and Inheritance - http://docs.oracle.com/javase/tutorial/java/IandI/index.html • Tools, tips and tricks for Unit Testing Java applications - http://www.junit.org