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

Pi j2.3 objects

  • 1.
    Programming in Java 5-dayworkshop OOP Objects Matt Collison JP Morgan Chase 2021 PiJ2.3: OOP Objects
  • 2.
    Four principles ofOOP: 1.Encapsulation – defining a class 2.Abstraction – modifying the objects •Generalisation through standardization 3.Inheritance – extending classes 4.Polymorphism – implementing interfaces
  • 3.
    How do weachieve 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 • ClassesCamelCase, 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 Accessinginstance 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 CANand 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 - staticmethod restrictions public static int idCounter() { int s = getSpeed();//Error! return idCounter; }
  • 12.
    Example – create/updateRectangleApp.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 doublewidth; 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 • InJava 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(doublew, 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 Ingeneral, 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 Toachieve 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 classStudent { 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 workshophomepage 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 • ThinkJava: 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