SlideShare a Scribd company logo
1 of 47
Java 102: Intro to Object-oriented
Programming with Java
Introduction
• Your Name: Manuela Grindei
• Your day job: Software Developer @ Gamesys
• Your last holiday destination: Dublin
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
• IDEs replace the slashes with a dot by
convention
Hands-on Exercise
Creating Objects
Exercise: Creating Objects
• Create a new Java project named Java102
• Create a new package named exercise.carfactory
• Create a class named Car in the exercise.carfactory
package
• Add color, make and model properties to the Car class
• Create a java program named CarFactory (in same
package) that creates two instances of the class Car,
changes their colors to Blue and Pink and prints a message
to the console
• Run the class CarFactory and observe the message in the
Console
Solution: Creating Objects
package exercise.creatingobjects;
public class Car {
String make;
String model;
String color;
}
package exercise.creatingobjects;
public class CarFactory {
public static void main(String[] args) {
Car firstCar = new Car();
Car secondCar = new Car();
firstCar.color = "Blue";
secondCar.color = "Pink";
System.out.println("Just finished painting new cars");
}
}
Car.java
CarFactory.java
Functions
• A sequence of program instructions that perform
a specific task that are packaged as a unit
• Takes 0 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
– Take you beyond pre-packaged libraries
– You build the functionality you need
• Process outline
– 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
Exercise: Working with Methods
• What happens when you compile and run the
following code?
public class Cubes {
static int cube (int i){
int j = i * i * i;
return j;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i=0 ;i<= N; i++) {
System.out.println(i + " " + cube(i));
}
}
}
Solution: Working with Methods
public class Cubes {
static int cube (int i){
int j = i * i * i;
return j;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i=0 ;i<= N; i++) {
System.out.println(i + " " + cube(i));
}
}
}
% java Cubes 6
0 0
1 1
2 8
3 27
4 64
5 125
6 216
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
Exercise : Method Overloading
• Create a new package named exercise.methodoverloading
• Create a BasicRateTax class with a method calcTax() that returns 20% of a fixed
base income of £1000
• Create a java program named TaxCollector that creates a new BasicRateTax object,
calls the calcTax() method and prints the output to the console
• Run the TaxCollector program and ensure it always prints 200.00 as calculated tax
• Add new calcTax() method to BasicRateTax class that takes a double grossIncome
parameter and calculates the tax as 20% of the grossIncome if it’s greater than the
base income of £1000
• Change the TaxCollector program to call the new calcTax(double grossIncome)
method and passing the gross Income value from the command line
• Run the TaxCollector program and see if the tax is correctly calculated.
• Re-run the program with different Gross Income values and check the output
Solution: Method Overloading
package exercise.methodoverloading;
public class BasicRateTax {
private static final double BASE_INCOME = 1000.00;
private static final double BASIC_TAX_RATE = 0.20;
public double calcTax (){
return BASE_INCOME * BASIC_TAX_RATE;
}
public double calcTax(double grossIncome){
if (grossIncome < BASE_INCOME){
return calcTax();
}
return grossIncome * BASIC_TAX_RATE;
}
}
Solution: Method Overloading
package exercise.methodoverloading;
public class TaxCollector {
public static void main(String[] args) {
double grossIncome = Double.parseDouble(args[0]);
BasicRateTax taxCalculator = new BasicRateTax();
double tax = taxCalculator.calcTax(grossIncome);
System.out.println("Tax due is " + tax);
}
}
% java TaxCollector 2000
Tax due is 400.0
% java TaxCollector 10000
Tax due is 2000.0
Inheritance
• Ability to define a new class based on an existing one
e.g. let’s 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
Exercise: Inheritance
• Create a new package named exercise.inheritance
• Create a class named HigherRateTax in the exercise.inheritance package that
extends BasicRateTax and add an empty calcTax(double grossIncome) method
• Add the code to HigherRateTax.calcTax(double grossIncome) method to calculate
the tax as follows:
– 20% of grossIncome if up to £34,000 (hint: reuse the BasicRateTax.calcTax(double
grossIncom) method)
– 40% of grossIncome if above £34,000 but less than £150,000
– 50% of grossIncome if £150,000 or above
• Run the existing TaxCollector program with some large gross income amounts and
observe that your changes didn’t have any effect on the calculate tax. Why?
• Change the code of the TaxCollector to instantiate HigherRateTax instead of
BasicRateTax
• Run the TaxCollector program again and observe that now the new percentage is
properly applied. You are now using the overridden version of the method
calcTax().
Solution: Inheritance
package exercise.inheritance;
import exercise.methodoverloading.BasicRateTax;
public class HigherRateTax extends BasicRateTax {
public double calcTax(double grossIncome){
double tax = 0.0;
if (grossIncome <=34000.00){
tax = super.calcTax(grossIncome);
} else if (grossIncome > 34000 && grossIncome <=150000) {
tax = grossIncome * 0.40;
} else if (grossIncome > 150000){
tax = grossIncome * 0.50;
}
return tax;
}
}
Solution: Inheritance
package exercise.methodoverloading;
import exercise.inheritance.HigherRateTax;
public class TaxCollector {
public static void main(String[] args) {
double grossIncome = Double.parseDouble(args[0]);
BasicRateTax taxCalculator = new HigherRateTax ();
double tax = taxCalculator.calcTax(grossIncome);
System.out.println("Tax due is " + tax);
}
}
% java TaxCollector 51000
Tax due is 20400.0
% java TaxCollector 32000
Tax due is 6400.0
% java TaxCollector 155000
Tax due is 77500.0
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
Exercise: Using Libraries
• Create a new package named exercise.libraryclient
• Create a class named CardDealer with an empty
deal() method that takes no arguments and returns
a String
• Implement the card dealer to use the StdRandom
library to deal playing cards randomly from an
infinite deck of cards
• Create a CardDealerTest program to test the
CardDealer class
Exercise: Using the StdRandom Library
public class CardDealer {
private static final String[] SUITES = { "D", "H", "C", "S"
};
private static final int TOTAL_CARDS_PER_SUITE = 13;
public String deal() {
// select a random suite
String suite = SUITES[StdRandom.uniform(SUITES.length)];
// select a random rank
int rank = StdRandom.uniform (TOTAL_CARDS_PER_SUITE ) +
1;
String card = rank + suite;
// return the dealt card
return card;
}
}
Testing the CardDealer Program
public class CardDealerTest {
public static void main(String[] args) {
CardDealer dealer = new CardDealer();
for (int i=0;i<5;i++){
String card = dealer.deal();
System.out.println( “ Card “ + i + “ is “ + card);
}
}
}
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

Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScriptpcnmtutorials
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arraysHassan Dar
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Steven Smith
 
Html,javascript & css
Html,javascript & cssHtml,javascript & css
Html,javascript & cssPredhin Sapru
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesAbdul Rahman Sherzad
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smellsPaul Nguyen
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Eyal Vardi
 

What's hot (20)

7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Web Development syllabus
Web Development syllabusWeb Development syllabus
Web Development syllabus
 
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
2. Classes | Object Oriented Programming in JavaScript | ES6 | JavaScript
 
Html training slide
Html training slideHtml training slide
Html training slide
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
 
Html,javascript & css
Html,javascript & cssHtml,javascript & css
Html,javascript & css
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Html basics
Html basicsHtml basics
Html basics
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Refactoring and code smells
Refactoring and code smellsRefactoring and code smells
Refactoring and code smells
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Java threads
Java threadsJava threads
Java threads
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Html
HtmlHtml
Html
 

Similar to Java 102

Java 102 intro to object-oriented programming in java - exercises
Java 102   intro to object-oriented programming in java - exercisesJava 102   intro to object-oriented programming in java - exercises
Java 102 intro to object-oriented programming in java - exercisesagorolabs
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
exercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdfexercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdfenodani2008
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019Paulo Clavijo
 
Cis 247 all i labs
Cis 247 all i labsCis 247 all i labs
Cis 247 all i labsccis224477
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engineWO Community
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at JetC4Media
 
Finding the Right Testing Tool for the Job
Finding the Right Testing Tool for the JobFinding the Right Testing Tool for the Job
Finding the Right Testing Tool for the JobCiaranMcNulty
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Procedure to create_the_calculator_application java
Procedure to create_the_calculator_application javaProcedure to create_the_calculator_application java
Procedure to create_the_calculator_application javagthe
 
Week10 packages using objects in objects
Week10 packages using objects in objectsWeek10 packages using objects in objects
Week10 packages using objects in objectskjkleindorfer
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder paramisoft
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsKuntal Bhowmick
 

Similar to Java 102 (20)

Java 102 intro to object-oriented programming in java - exercises
Java 102   intro to object-oriented programming in java - exercisesJava 102   intro to object-oriented programming in java - exercises
Java 102 intro to object-oriented programming in java - exercises
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
exercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdfexercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdf
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
 
Cis 247 all i labs
Cis 247 all i labsCis 247 all i labs
Cis 247 all i labs
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at Jet
 
Finding the Right Testing Tool for the Job
Finding the Right Testing Tool for the JobFinding the Right Testing Tool for the Job
Finding the Right Testing Tool for the Job
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Procedure to create_the_calculator_application java
Procedure to create_the_calculator_application javaProcedure to create_the_calculator_application java
Procedure to create_the_calculator_application java
 
Week10 packages using objects in objects
Week10 packages using objects in objectsWeek10 packages using objects in objects
Week10 packages using objects in objects
 
C++ Lab Maual.pdf
C++ Lab Maual.pdfC++ Lab Maual.pdf
C++ Lab Maual.pdf
 
C++ Lab Maual.pdf
C++ Lab Maual.pdfC++ Lab Maual.pdf
C++ Lab Maual.pdf
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
 

More from Manuela Grindei

More from Manuela Grindei (6)

TDD Training
TDD TrainingTDD Training
TDD Training
 
Java 104
Java 104Java 104
Java 104
 
Java 103
Java 103Java 103
Java 103
 
Continuous delivery - takeaways
Continuous delivery - takeawaysContinuous delivery - takeaways
Continuous delivery - takeaways
 
Release it! - Takeaways
Release it! - TakeawaysRelease it! - Takeaways
Release it! - Takeaways
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 

Recently uploaded

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
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfryanfarris8
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2
 
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and ApplicationsWSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and ApplicationsWSO2
 
WSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2
 
WSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million PeopleWSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million PeopleWSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Eraconfluent
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...WSO2
 
Driving Innovation: Scania's API Revolution with WSO2
Driving Innovation: Scania's API Revolution with WSO2Driving Innovation: Scania's API Revolution with WSO2
Driving Innovation: Scania's API Revolution with WSO2WSO2
 

Recently uploaded (20)

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
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
 
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and ApplicationsWSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
WSO2CON 2024 - Architecting AI in the Enterprise: APIs and Applications
 
WSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid Environments
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
 
WSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million PeopleWSO2Con2024 - Unleashing the Financial Potential of 13 Million People
WSO2Con2024 - Unleashing the Financial Potential of 13 Million People
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Era
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
 
Driving Innovation: Scania's API Revolution with WSO2
Driving Innovation: Scania's API Revolution with WSO2Driving Innovation: Scania's API Revolution with WSO2
Driving Innovation: Scania's API Revolution with WSO2
 

Java 102

  • 1. Java 102: Intro to Object-oriented Programming with Java
  • 2. Introduction • Your Name: Manuela Grindei • Your day job: Software Developer @ Gamesys • Your last holiday destination: Dublin
  • 3. Java 102 • Object-oriented Programming – Fundamentals • Classes & Objects • Methods & Constructors • Encapsulation • Inheritance – Libraries & Clients
  • 4. Java 102: Intro to Object- oriented Programming with Java Fundamentals
  • 5. 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)
  • 7. 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
  • 8. 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”;!
  • 9. 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
  • 10. 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 • IDEs replace the slashes with a dot by convention
  • 12. Exercise: Creating Objects • Create a new Java project named Java102 • Create a new package named exercise.carfactory • Create a class named Car in the exercise.carfactory package • Add color, make and model properties to the Car class • Create a java program named CarFactory (in same package) that creates two instances of the class Car, changes their colors to Blue and Pink and prints a message to the console • Run the class CarFactory and observe the message in the Console
  • 13. Solution: Creating Objects package exercise.creatingobjects; public class Car { String make; String model; String color; } package exercise.creatingobjects; public class CarFactory { public static void main(String[] args) { Car firstCar = new Car(); Car secondCar = new Car(); firstCar.color = "Blue"; secondCar.color = "Pink"; System.out.println("Just finished painting new cars"); } } Car.java CarFactory.java
  • 14. Functions • A sequence of program instructions that perform a specific task that are packaged as a unit • Takes 0 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
  • 15. 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
  • 16. Benefits of Methods • Methods enable you to build a new layer of abstraction – Take you beyond pre-packaged libraries – You build the functionality you need • Process outline – Step 1: identify a useful feature – Step 2: implement it – Step 3: use it (re-use it in any of your programs)
  • 17. Anatomy of a Java Method
  • 18. 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
  • 20. Exercise: Working with Methods • What happens when you compile and run the following code? public class Cubes { static int cube (int i){ int j = i * i * i; return j; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i=0 ;i<= N; i++) { System.out.println(i + " " + cube(i)); } } }
  • 21. Solution: Working with Methods public class Cubes { static int cube (int i){ int j = i * i * i; return j; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i=0 ;i<= N; i++) { System.out.println(i + " " + cube(i)); } } } % java Cubes 6 0 0 1 1 2 8 3 27 4 64 5 125 6 216
  • 22. 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; } }
  • 23. 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 } }
  • 25. Exercise : Method Overloading • Create a new package named exercise.methodoverloading • Create a BasicRateTax class with a method calcTax() that returns 20% of a fixed base income of £1000 • Create a java program named TaxCollector that creates a new BasicRateTax object, calls the calcTax() method and prints the output to the console • Run the TaxCollector program and ensure it always prints 200.00 as calculated tax • Add new calcTax() method to BasicRateTax class that takes a double grossIncome parameter and calculates the tax as 20% of the grossIncome if it’s greater than the base income of £1000 • Change the TaxCollector program to call the new calcTax(double grossIncome) method and passing the gross Income value from the command line • Run the TaxCollector program and see if the tax is correctly calculated. • Re-run the program with different Gross Income values and check the output
  • 26. Solution: Method Overloading package exercise.methodoverloading; public class BasicRateTax { private static final double BASE_INCOME = 1000.00; private static final double BASIC_TAX_RATE = 0.20; public double calcTax (){ return BASE_INCOME * BASIC_TAX_RATE; } public double calcTax(double grossIncome){ if (grossIncome < BASE_INCOME){ return calcTax(); } return grossIncome * BASIC_TAX_RATE; } }
  • 27. Solution: Method Overloading package exercise.methodoverloading; public class TaxCollector { public static void main(String[] args) { double grossIncome = Double.parseDouble(args[0]); BasicRateTax taxCalculator = new BasicRateTax(); double tax = taxCalculator.calcTax(grossIncome); System.out.println("Tax due is " + tax); } } % java TaxCollector 2000 Tax due is 400.0 % java TaxCollector 10000 Tax due is 2000.0
  • 28. Inheritance • Ability to define a new class based on an existing one e.g. let’s create a James Bond Car from our existing Car class
  • 30. 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
  • 32. Exercise: Inheritance • Create a new package named exercise.inheritance • Create a class named HigherRateTax in the exercise.inheritance package that extends BasicRateTax and add an empty calcTax(double grossIncome) method • Add the code to HigherRateTax.calcTax(double grossIncome) method to calculate the tax as follows: – 20% of grossIncome if up to £34,000 (hint: reuse the BasicRateTax.calcTax(double grossIncom) method) – 40% of grossIncome if above £34,000 but less than £150,000 – 50% of grossIncome if £150,000 or above • Run the existing TaxCollector program with some large gross income amounts and observe that your changes didn’t have any effect on the calculate tax. Why? • Change the code of the TaxCollector to instantiate HigherRateTax instead of BasicRateTax • Run the TaxCollector program again and observe that now the new percentage is properly applied. You are now using the overridden version of the method calcTax().
  • 33. Solution: Inheritance package exercise.inheritance; import exercise.methodoverloading.BasicRateTax; public class HigherRateTax extends BasicRateTax { public double calcTax(double grossIncome){ double tax = 0.0; if (grossIncome <=34000.00){ tax = super.calcTax(grossIncome); } else if (grossIncome > 34000 && grossIncome <=150000) { tax = grossIncome * 0.40; } else if (grossIncome > 150000){ tax = grossIncome * 0.50; } return tax; } }
  • 34. Solution: Inheritance package exercise.methodoverloading; import exercise.inheritance.HigherRateTax; public class TaxCollector { public static void main(String[] args) { double grossIncome = Double.parseDouble(args[0]); BasicRateTax taxCalculator = new HigherRateTax (); double tax = taxCalculator.calcTax(grossIncome); System.out.println("Tax due is " + tax); } } % java TaxCollector 51000 Tax due is 20400.0 % java TaxCollector 32000 Tax due is 6400.0 % java TaxCollector 155000 Tax due is 77500.0
  • 35. 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
  • 36. Java 102: Intro to Object-oriented Programming with Java Java Libraries
  • 37. 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
  • 38. Example: Standard Random • A library to generate pseudo-random numbers Source: http://search.dilbert.com/comic/Tour%20Of%20Accounting
  • 40. 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; } }
  • 42. Exercise: Using Libraries • Create a new package named exercise.libraryclient • Create a class named CardDealer with an empty deal() method that takes no arguments and returns a String • Implement the card dealer to use the StdRandom library to deal playing cards randomly from an infinite deck of cards • Create a CardDealerTest program to test the CardDealer class
  • 43. Exercise: Using the StdRandom Library public class CardDealer { private static final String[] SUITES = { "D", "H", "C", "S" }; private static final int TOTAL_CARDS_PER_SUITE = 13; public String deal() { // select a random suite String suite = SUITES[StdRandom.uniform(SUITES.length)]; // select a random rank int rank = StdRandom.uniform (TOTAL_CARDS_PER_SUITE ) + 1; String card = rank + suite; // return the dealt card return card; } }
  • 44. Testing the CardDealer Program public class CardDealerTest { public static void main(String[] args) { CardDealer dealer = new CardDealer(); for (int i=0;i<5;i++){ String card = dealer.deal(); System.out.println( “ Card “ + i + “ is “ + card); } } }
  • 45. 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
  • 46. 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...
  • 47. 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