SlideShare a Scribd company logo
Programming in Java
5-day workshop
OOP Objects
Matt Collison
JP Morgan Chase 2021
PiJ2.3: OOP Objects
Four principles of OOP:
1.Encapsulation – defining a class
2.Abstraction – modifying the objects
•Generalisation through standardization
3.Inheritance – extending classes
4.Polymorphism – implementing interfaces
How do we achieve abstraction through OOP?
• Classes and objects: The first order of abstraction. class new
• There are lots of things that the same but with different attribute values.
• For example people – we all have a name, a height, we have interests and friends.
Think of a social media platform. Everyone has a profile but everyone’s profile is
unique.
• Class inheritance: The second order of abstraction extends
• The definitions for things can share common features.
• For example the administrator account and a user account both require a username,
password and contact details. Each of these account would extend a common
‘parent’ account definition.
• Polymorphism: The third order of abstraction implements
• The definitions for things can share features but complete them in different ways to
achieve different behaviours. For example an e-commerce store must have a databse
binding, a layout schema for the UI but the specifc implementations are unique.
These aren’t just different values but different functions.
Classes and objects
• Classes are the types
• Objects are the instances
Class object = <expression>
• Classes are made up of Objects are instantiated with:
• Attributes – fields to describe the class
• Constructors – constrain how you can create the object
• Methods – functions to describe it’s behaviour
Note the upper case letter usage
in the identifiers
Naming conventions
• Classes CamelCase, each word starting upper case
• E.g., BouncingBall, HelloWorld, ParetoArchive
• Methods and Attributes camelCase with lower case first letter
• E.g., width, originX, borrowDate
• E.g., brake, addValueToArchive, resetButton
Object syntax – create RectangleApp.java
Syntax:
Rectangle rectSmall = new Rectangle();
Or:
• Rectangle rectLarge;
• rectLarge = new Rectangle(10.0,15.0);
Creating an object consists of three steps:
1. Declaration.
2. Instantiation: The new keyword is used to create the object, i.e., a block
of memory space is allocated for this object.
3. Initialization: The new keyword is followed by a call to a constructor
which initializes the new object.
Using an object
Accessing instance members (i.e, attributes and methods):
• First, create an instance/object of the class;
• Then, use the dot operator (.) to reference the member attributes or
member methods.
Rectangle rect1 = new Rectangle(10,15,2,4);
double w = rect1.width;
rect1.move(2.5,0);
double area = new Rectangle(10,15).getArea();
Anonymous object
Using an object
• Accessing static members:
• Option 1: the same as how to reference instance members.
• Option 2 (most recommended): No need creating an instance, instead,
invoked with the class name directly.
int n = Rectangle.NUMBER OF SIDES;
boolean b = Rectangle.isOverlapped(rect1, rect2);
double a = Math.sqrt(10); //Math offered many static methods and
//static fields, e.g., Math.PI
static members
• Example: Suppose you create a Bicycle class, besides its basic
attributes about bicycles, you also want to assign each bicycle a
unique ID number, beginning with 1 for the first bicycle. The ID
increases whenever a new bicycle object is created.
• Q1: Is the ID an instance attribute or a static attribute?
• private int id;//instance
• Q2: Is the numberOfBicycles an instance attributes or a static
attribute?
• private static int idCounter = 0;//static
static methods CAN and CANNOT
Instance methods:
• can access instance attributes and instance methods directly.
• can access static attributes and static methods directly.
static methods
• can access static attributes and static methods directly.
• CANNOT access instance attributes or instance methods directly, they
must use an object reference.
• CANNOT use the this keyword as there is no instance for this to refer
to.
Example - static method restrictions
public static int idCounter() {
int s = getSpeed();//Error!
return idCounter;
}
Example – create/update RectangleApp.java
public class RectangleApp { //To be excutable, need a main method
public static void main( String[] args ) {
Rectangle myRect; //myRect is not instantiated yet
myRect = new Rectangle(20.0, 8.0);//instantiated
//static field
System.out.println("Any rectangle has " + Rectangle.NUMBER_OF_SIDES +
" sides");
//instance fields
System.out.println("myRect’s origin:"
+myRect.originX + "," + myRect.originY);
//calling methods
System.out.println("Area: " + myRect.getArea());
myRect.move(2,10); //the object’s state is changed
System.out.println("The origin moves to:"
+myRect.originX + "," + myRect.originY);
}
}
Access modifiers
private double width;
public double getArea() { ... }
public: accessible by the entire “world” (all other classes that can access it).
private: accessible only within that class.
protected: accessible in the same package and all subclasses.
Default (i.e. if no modifier specified): accessible only by other classes/objects
in the same package.
NOTE: A class cannot be private or protected except nested class.
Example access errors
// An example for access modifier
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
void outMsg() { msg(); };
}
public class ModifierApp{
public static void main(String args[]){
A objA=new A();//call the default no-arg constructor
System.out.println(objA.data);//Compile time error!
obj.msg();//Compile time error!
objA.outMsg();
}
}
Object reference
• In Java a variable referring to an object is a reference to the memory address where the object is stored.
Rectangle rect1 = new Rectangle(10,15);
Rectangle rect2;
rect2 = rect1; //rect2 references the same memory address as rect1
rect2.width = 5;
Rectangle rect3 = new Rectangle(5,15);
Q1: What is the value of rect1.width?
• 5
Q2: Is rect1==rect2 true or false?
• true
Q3: Is rect2==rect3 true of false?
• false
this keyword
public Rectangle(double w, double h, double originX, double originY) {
this.originX = originX;
this.originY = originY;
width = w;
height = h;
}
• this is used as a reference to the object of the current class, within an instance
method or a constructor. It can be this.fieldname this.methodname(...) this(...)
NOTE: The keyword this is used only within instance methods, not static methods.
• Why?
this in constructors
In general, the this keyword is used to:
• Differentiate the attributes from method arguments if they have same names,
within a constructor or a method.
• this.originX = originX;
• Call one type of constructor from another within a class.
• It is known as explicit constructor invocation.
class Student {
String name;
int age;
Student() {
this("Alex", 20);//call another constructor
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Encapsulation in Java
To achieve encapsulation (or called a program/class is well
encapsulated) in Java:
• Declare the attributes of a class as private.
• Provide public setter and getter methods to modify and view the
attributes.
Getters and setters
class Student {
private String name; //good to define private fields
private int age;
public Student(String name, int age){
this.name = name;
this.age = age;
}
// 2 setter methods
public void setName(String name){ this.name = name;}
public void setAge(int age){ this.age = age;}
// 2 getter methods
public String getName(){return name;}
public int getAge(){return age;}
}
Accessing object attributes
• Outside of the Student class
Student e = new Student("Alex", 20);
e.age = 21; //Error! can’t access private members
e.setAge(21); //modify the age via setter method
String name = e.getName(); //read the name
Advantages of encapsulation
• It enforces modularity.
• It improves maintainability.
• A class can have total control over what is stored in its fields. The field
can be made
• read-only - If we don’t define its setter method.
• write-only - If we don’t define its getter method
OOP Principles
• Abstraction: hiding all but relevant data in order to reduce complexity and
increase efficiency.
• Encapsulation is a kind of abstraction.
• Abstaction is also accomplished standardising definitions.
• Inheritance: classes can be derived from other classes, thereby inheriting
fields and methods from those classes.
• Polymorphism: performing a single action in different ways.
• Method overloading is a type of polymorphism - compile time polymorphism.
• Method overriding is another type of polymorphism - runtime polymorphism.
Note: we will explain inheritance and polymorphism later in the workshop
day 3
Learning resources
The workshop homepage
https://mcollison.github.io/JPMC-java-intro-2021/
The course materials
https://mcollison.github.io/java-programming-foundations/
• Session worksheets – updated each week
Additional resources
• Think Java: How to think like a computer scientist
• Allen B Downey (O’Reilly Press)
• Available under Creative Commons license
• https://greenteapress.com/wp/think-java-2e/
• Oracle central Java Documentation –
https://docs.oracle.com/javase/8/docs/api/
• Other sources:
• W3Schools Java - https://www.w3schools.com/java/
• stack overflow - https://stackoverflow.com/
• Coding bat - https://codingbat.com/java
Ad

Recommended

11 Using classes and objects
11 Using classes and objects
maznabili
 
Core Java Concepts
Core Java Concepts
mdfkhan625
 
Java Generics
Java Generics
DeeptiJava
 
Java: Objects and Object References
Java: Objects and Object References
Tareq Hasan
 
Oops Concept Java
Oops Concept Java
Kamlesh Singh
 
Java basic
Java basic
Sonam Sharma
 
Lect 1-class and object
Lect 1-class and object
Fajar Baskoro
 
Class and Objects in Java
Class and Objects in Java
Spotle.ai
 
Object and class
Object and class
mohit tripathi
 
Lect 1-java object-classes
Lect 1-java object-classes
Fajar Baskoro
 
Object and Classes in Java
Object and Classes in Java
backdoor
 
Oop java
Oop java
Minal Maniar
 
Object Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
C++ Programming Course
C++ Programming Course
Dennis Chang
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
kjkleindorfer
 
ITFT-Classes and object in java
ITFT-Classes and object in java
Atul Sehdev
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
Object Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Class and object in C++
Class and object in C++
rprajat007
 
Introduction to java and oop
Introduction to java and oop
baabtra.com - No. 1 supplier of quality freshers
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Core java concepts
Core java concepts
laratechnologies
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Generics in java
Generics in java
suraj pandey
 
Pi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
Core java concepts
Core java concepts
Ram132
 
Chapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 

More Related Content

What's hot (20)

Object and class
Object and class
mohit tripathi
 
Lect 1-java object-classes
Lect 1-java object-classes
Fajar Baskoro
 
Object and Classes in Java
Object and Classes in Java
backdoor
 
Oop java
Oop java
Minal Maniar
 
Object Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
C++ Programming Course
C++ Programming Course
Dennis Chang
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
kjkleindorfer
 
ITFT-Classes and object in java
ITFT-Classes and object in java
Atul Sehdev
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
Object Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Class and object in C++
Class and object in C++
rprajat007
 
Introduction to java and oop
Introduction to java and oop
baabtra.com - No. 1 supplier of quality freshers
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Core java concepts
Core java concepts
laratechnologies
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Generics in java
Generics in java
suraj pandey
 
Pi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
Core java concepts
Core java concepts
Ram132
 
Chapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Lect 1-java object-classes
Lect 1-java object-classes
Fajar Baskoro
 
Object and Classes in Java
Object and Classes in Java
backdoor
 
Object Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
C++ Programming Course
C++ Programming Course
Dennis Chang
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
kjkleindorfer
 
ITFT-Classes and object in java
ITFT-Classes and object in java
Atul Sehdev
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
Object Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Class and object in C++
Class and object in C++
rprajat007
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Pi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
Core java concepts
Core java concepts
Ram132
 

Similar to Pi j2.3 objects (20)

Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
class as the basis.pptx
class as the basis.pptx
Epsiba1
 
C# classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
oop 3.pptx
oop 3.pptx
OsamaMuhammad18
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
07slide.ppt
07slide.ppt
NuurAxmed2
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
Lecture 5.pptx
Lecture 5.pptx
AshutoshTrivedi30
 
2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
Object oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
JAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 
Ch-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
Chapter- 2 Introduction to Class and Object.pdf
Chapter- 2 Introduction to Class and Object.pdf
joshua211619
 
object oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
object oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptx
SarthakSrivastava70
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
class as the basis.pptx
class as the basis.pptx
Epsiba1
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
2 Object-oriented programghgrtrdwwe.pptx
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
Object oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
JAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 
Chapter- 2 Introduction to Class and Object.pdf
Chapter- 2 Introduction to Class and Object.pdf
joshua211619
 
object oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
object oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
Ad

More from mcollison (10)

Pi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison
 
Pi j4.1 packages
Pi j4.1 packages
mcollison
 
Pi j3.1 inheritance
Pi j3.1 inheritance
mcollison
 
Pi j3.4 data-structures
Pi j3.4 data-structures
mcollison
 
Pi j2.2 classes
Pi j2.2 classes
mcollison
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introduction
mcollison
 
Pi j1.4 loops
Pi j1.4 loops
mcollison
 
Pi j1.3 operators
Pi j1.3 operators
mcollison
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignment
mcollison
 
Pi j1.1 what-is-java
Pi j1.1 what-is-java
mcollison
 
Pi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison
 
Pi j4.1 packages
Pi j4.1 packages
mcollison
 
Pi j3.1 inheritance
Pi j3.1 inheritance
mcollison
 
Pi j3.4 data-structures
Pi j3.4 data-structures
mcollison
 
Pi j2.2 classes
Pi j2.2 classes
mcollison
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introduction
mcollison
 
Pi j1.4 loops
Pi j1.4 loops
mcollison
 
Pi j1.3 operators
Pi j1.3 operators
mcollison
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignment
mcollison
 
Pi j1.1 what-is-java
Pi j1.1 what-is-java
mcollison
 
Ad

Recently uploaded (20)

Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
June 2025 Progress Update With Board Call_In process.pptx
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
How to use search fetch method in Odoo 18
How to use search fetch method in Odoo 18
Celine George
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
INDUCTIVE EFFECT slide for first prof pharamacy students
INDUCTIVE EFFECT slide for first prof pharamacy students
SHABNAM FAIZ
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
Intellectual Property Right (Jurisprudence).pptx
Intellectual Property Right (Jurisprudence).pptx
Vishal Chanalia
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
How to use search fetch method in Odoo 18
How to use search fetch method in Odoo 18
Celine George
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
INDUCTIVE EFFECT slide for first prof pharamacy students
INDUCTIVE EFFECT slide for first prof pharamacy students
SHABNAM FAIZ
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
Intellectual Property Right (Jurisprudence).pptx
Intellectual Property Right (Jurisprudence).pptx
Vishal Chanalia
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 

Pi j2.3 objects

  • 1. Programming in Java 5-day workshop OOP Objects Matt Collison JP Morgan Chase 2021 PiJ2.3: OOP Objects
  • 2. Four principles of OOP: 1.Encapsulation – defining a class 2.Abstraction – modifying the objects •Generalisation through standardization 3.Inheritance – extending classes 4.Polymorphism – implementing interfaces
  • 3. How do we achieve abstraction through OOP? • Classes and objects: The first order of abstraction. class new • There are lots of things that the same but with different attribute values. • For example people – we all have a name, a height, we have interests and friends. Think of a social media platform. Everyone has a profile but everyone’s profile is unique. • Class inheritance: The second order of abstraction extends • The definitions for things can share common features. • For example the administrator account and a user account both require a username, password and contact details. Each of these account would extend a common ‘parent’ account definition. • Polymorphism: The third order of abstraction implements • The definitions for things can share features but complete them in different ways to achieve different behaviours. For example an e-commerce store must have a databse binding, a layout schema for the UI but the specifc implementations are unique. These aren’t just different values but different functions.
  • 4. Classes and objects • Classes are the types • Objects are the instances Class object = <expression> • Classes are made up of Objects are instantiated with: • Attributes – fields to describe the class • Constructors – constrain how you can create the object • Methods – functions to describe it’s behaviour Note the upper case letter usage in the identifiers
  • 5. Naming conventions • Classes CamelCase, each word starting upper case • E.g., BouncingBall, HelloWorld, ParetoArchive • Methods and Attributes camelCase with lower case first letter • E.g., width, originX, borrowDate • E.g., brake, addValueToArchive, resetButton
  • 6. Object syntax – create RectangleApp.java Syntax: Rectangle rectSmall = new Rectangle(); Or: • Rectangle rectLarge; • rectLarge = new Rectangle(10.0,15.0); Creating an object consists of three steps: 1. Declaration. 2. Instantiation: The new keyword is used to create the object, i.e., a block of memory space is allocated for this object. 3. Initialization: The new keyword is followed by a call to a constructor which initializes the new object.
  • 7. Using an object Accessing instance members (i.e, attributes and methods): • First, create an instance/object of the class; • Then, use the dot operator (.) to reference the member attributes or member methods. Rectangle rect1 = new Rectangle(10,15,2,4); double w = rect1.width; rect1.move(2.5,0); double area = new Rectangle(10,15).getArea(); Anonymous object
  • 8. Using an object • Accessing static members: • Option 1: the same as how to reference instance members. • Option 2 (most recommended): No need creating an instance, instead, invoked with the class name directly. int n = Rectangle.NUMBER OF SIDES; boolean b = Rectangle.isOverlapped(rect1, rect2); double a = Math.sqrt(10); //Math offered many static methods and //static fields, e.g., Math.PI
  • 9. static members • Example: Suppose you create a Bicycle class, besides its basic attributes about bicycles, you also want to assign each bicycle a unique ID number, beginning with 1 for the first bicycle. The ID increases whenever a new bicycle object is created. • Q1: Is the ID an instance attribute or a static attribute? • private int id;//instance • Q2: Is the numberOfBicycles an instance attributes or a static attribute? • private static int idCounter = 0;//static
  • 10. static methods CAN and CANNOT Instance methods: • can access instance attributes and instance methods directly. • can access static attributes and static methods directly. static methods • can access static attributes and static methods directly. • CANNOT access instance attributes or instance methods directly, they must use an object reference. • CANNOT use the this keyword as there is no instance for this to refer to.
  • 11. Example - static method restrictions public static int idCounter() { int s = getSpeed();//Error! return idCounter; }
  • 12. Example – create/update RectangleApp.java public class RectangleApp { //To be excutable, need a main method public static void main( String[] args ) { Rectangle myRect; //myRect is not instantiated yet myRect = new Rectangle(20.0, 8.0);//instantiated //static field System.out.println("Any rectangle has " + Rectangle.NUMBER_OF_SIDES + " sides"); //instance fields System.out.println("myRect’s origin:" +myRect.originX + "," + myRect.originY); //calling methods System.out.println("Area: " + myRect.getArea()); myRect.move(2,10); //the object’s state is changed System.out.println("The origin moves to:" +myRect.originX + "," + myRect.originY); } }
  • 13. Access modifiers private double width; public double getArea() { ... } public: accessible by the entire “world” (all other classes that can access it). private: accessible only within that class. protected: accessible in the same package and all subclasses. Default (i.e. if no modifier specified): accessible only by other classes/objects in the same package. NOTE: A class cannot be private or protected except nested class.
  • 14. Example access errors // An example for access modifier class A{ private int data=40; private void msg(){System.out.println("Hello java");} void outMsg() { msg(); }; } public class ModifierApp{ public static void main(String args[]){ A objA=new A();//call the default no-arg constructor System.out.println(objA.data);//Compile time error! obj.msg();//Compile time error! objA.outMsg(); } }
  • 15. Object reference • In Java a variable referring to an object is a reference to the memory address where the object is stored. Rectangle rect1 = new Rectangle(10,15); Rectangle rect2; rect2 = rect1; //rect2 references the same memory address as rect1 rect2.width = 5; Rectangle rect3 = new Rectangle(5,15); Q1: What is the value of rect1.width? • 5 Q2: Is rect1==rect2 true or false? • true Q3: Is rect2==rect3 true of false? • false
  • 16. this keyword public Rectangle(double w, double h, double originX, double originY) { this.originX = originX; this.originY = originY; width = w; height = h; } • this is used as a reference to the object of the current class, within an instance method or a constructor. It can be this.fieldname this.methodname(...) this(...) NOTE: The keyword this is used only within instance methods, not static methods. • Why?
  • 17. this in constructors In general, the this keyword is used to: • Differentiate the attributes from method arguments if they have same names, within a constructor or a method. • this.originX = originX; • Call one type of constructor from another within a class. • It is known as explicit constructor invocation. class Student { String name; int age; Student() { this("Alex", 20);//call another constructor } Student(String name, int age) { this.name = name; this.age = age; } }
  • 18. Encapsulation in Java To achieve encapsulation (or called a program/class is well encapsulated) in Java: • Declare the attributes of a class as private. • Provide public setter and getter methods to modify and view the attributes.
  • 19. Getters and setters class Student { private String name; //good to define private fields private int age; public Student(String name, int age){ this.name = name; this.age = age; } // 2 setter methods public void setName(String name){ this.name = name;} public void setAge(int age){ this.age = age;} // 2 getter methods public String getName(){return name;} public int getAge(){return age;} }
  • 20. Accessing object attributes • Outside of the Student class Student e = new Student("Alex", 20); e.age = 21; //Error! can’t access private members e.setAge(21); //modify the age via setter method String name = e.getName(); //read the name
  • 21. Advantages of encapsulation • It enforces modularity. • It improves maintainability. • A class can have total control over what is stored in its fields. The field can be made • read-only - If we don’t define its setter method. • write-only - If we don’t define its getter method
  • 22. OOP Principles • Abstraction: hiding all but relevant data in order to reduce complexity and increase efficiency. • Encapsulation is a kind of abstraction. • Abstaction is also accomplished standardising definitions. • Inheritance: classes can be derived from other classes, thereby inheriting fields and methods from those classes. • Polymorphism: performing a single action in different ways. • Method overloading is a type of polymorphism - compile time polymorphism. • Method overriding is another type of polymorphism - runtime polymorphism. Note: we will explain inheritance and polymorphism later in the workshop day 3
  • 23. Learning resources The workshop homepage https://mcollison.github.io/JPMC-java-intro-2021/ The course materials https://mcollison.github.io/java-programming-foundations/ • Session worksheets – updated each week
  • 24. Additional resources • Think Java: How to think like a computer scientist • Allen B Downey (O’Reilly Press) • Available under Creative Commons license • https://greenteapress.com/wp/think-java-2e/ • Oracle central Java Documentation – https://docs.oracle.com/javase/8/docs/api/ • Other sources: • W3Schools Java - https://www.w3schools.com/java/ • stack overflow - https://stackoverflow.com/ • Coding bat - https://codingbat.com/java