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

More Related Content

PPT
11 Using classes and objects
PPT
Core Java Concepts
PPTX
Java Generics
PPT
Java: Objects and Object References
PPT
Oops Concept Java
PPT
Java basic
PPT
Lect 1-class and object
PDF
Class and Objects in Java
11 Using classes and objects
Core Java Concepts
Java Generics
Java: Objects and Object References
Oops Concept Java
Java basic
Lect 1-class and object
Class and Objects in Java

What's hot (20)

PPT
Object and class
PDF
Lect 1-java object-classes
PPT
Object and Classes in Java
PPT
Oop java
PDF
Object Oriented Programming in PHP
PPT
C++ Programming Course
PPTX
Week9 Intro to classes and objects in Java
PDF
ITFT-Classes and object in java
PPT
Core Java Programming | Data Type | operator | java Control Flow| Class 2
PPT
Object Oriented Programming with Java
PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
PPT
Class and object in C++
PDF
PPT
Java tutorial for Beginners and Entry Level
PPTX
Core java concepts
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PPT
Generics in java
PPTX
Pi j3.2 polymorphism
PPT
Core java concepts
PPTX
Chapter 05 classes and objects
Object and class
Lect 1-java object-classes
Object and Classes in Java
Oop java
Object Oriented Programming in PHP
C++ Programming Course
Week9 Intro to classes and objects in Java
ITFT-Classes and object in java
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Object Oriented Programming with Java
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Class and object in C++
Java tutorial for Beginners and Entry Level
Core java concepts
Basic Concepts of OOPs (Object Oriented Programming in Java)
Generics in java
Pi j3.2 polymorphism
Core java concepts
Chapter 05 classes and objects
Ad

Similar to Pi j2.3 objects (20)

PPT
Core Java unit no. 1 object and class ppt
PPT
Core Java unit no. 1 object and class ppt
PPTX
class as the basis.pptx
PPTX
C# classes objects
PPTX
oop 3.pptx
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
PPT
07slide.ppt
PPT
02._Object-Oriented_Programming_Concepts.ppt
PPTX
Class and Object.pptx from nit patna ece department
PPTX
Lecture 5.pptx
PPTX
2 Object-oriented programghgrtrdwwe.pptx
PPTX
Object oriented programming in java
PDF
JAVA Class Presentation.pdf Vsjsjsnheheh
PPTX
Ch-2ppt.pptx
PDF
Chapter- 2 Introduction to Class and Object.pdf
PPTX
object oriented porgramming using Java programming
PPTX
object oriented porgramming using Java programming
PDF
Java Programming - 04 object oriented in java
PPT
Ccourse 140618093931-phpapp02
PPTX
BCA Class and Object (3).pptx
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
class as the basis.pptx
C# classes objects
oop 3.pptx
Class and Object JAVA PROGRAMMING LANG .pdf
07slide.ppt
02._Object-Oriented_Programming_Concepts.ppt
Class and Object.pptx from nit patna ece department
Lecture 5.pptx
2 Object-oriented programghgrtrdwwe.pptx
Object oriented programming in java
JAVA Class Presentation.pdf Vsjsjsnheheh
Ch-2ppt.pptx
Chapter- 2 Introduction to Class and Object.pdf
object oriented porgramming using Java programming
object oriented porgramming using Java programming
Java Programming - 04 object oriented in java
Ccourse 140618093931-phpapp02
BCA Class and Object (3).pptx
Ad

More from mcollison (10)

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

Recently uploaded (20)

PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Institutional Correction lecture only . . .
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Complications of Minimal Access Surgery at WLH
STATICS OF THE RIGID BODIES Hibbelers.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Sports Quiz easy sports quiz sports quiz
Institutional Correction lecture only . . .
VCE English Exam - Section C Student Revision Booklet
102 student loan defaulters named and shamed – Is someone you know on the list?
Renaissance Architecture: A Journey from Faith to Humanism
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Microbial diseases, their pathogenesis and prophylaxis
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Anesthesia in Laparoscopic Surgery in India
Computing-Curriculum for Schools in Ghana
Final Presentation General Medicine 03-08-2024.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Complications of Minimal Access Surgery at WLH

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