Upload
others
View
8
Download
0
Embed Size (px)
Citation preview
Objects and Classes 1 / 32
Objects and Classes
COMPSCI 2S03
Mikhail Andrenkov
Department of Computing and Software
McMaster University
Week 6: Oct 24 - 28
Mikhail Andrenkov Objects and Classes 1 / 32
Objects and Classes 2 / 32
Outline
Outline
1 What is a Class?
2 Access Modi�ers
3 Class Instances
4 Class Constructors
5 Object References
6 Static vs. Dynamic
7 Object Inheritance
8 Reference vs. Object Equality
9 Overriding
10 Enumerations
Mikhail Andrenkov Objects and Classes 2 / 32
Objects and Classes 3 / 32
What is a Class?
What is a Class?
Inspiration: The real world is composed of discrete objects
Some objects share common features
Object-Oriented Programming (OOP): Programmingparadigm that models data and behaviour using �objects�
Class: Encapsulation of an object's properties; a template foran objectObject: An instance of a class
Mikhail Andrenkov Objects and Classes 3 / 32
Objects and Classes 4 / 32
What is a Class?
Example: Dog
Suppose we want to design a class to model dogs
What features do all dogs have in common?
1 Properties2 Actions
Mikhail Andrenkov Objects and Classes 4 / 32
Objects and Classes 5 / 32
What is a Class?
Example: Dog
Real World Java
Properties ?
Name ?
Breed ?
Age ?
Actions ?
Sleep ?
Eat ?
Bark ?
Note: Each property and action should have a corresponding
element in the Java class
Mikhail Andrenkov Objects and Classes 5 / 32
Objects and Classes 6 / 32
What is a Class?
Example: Dog
Real World Java
Properties Class Variables
Name String name;
Breed String breed;
Age int age;
Actions Class Methods
Sleep void sleep();
Eat void eat(String food);
Bark String bark();
Property → Variable
Action → Method
Mikhail Andrenkov Objects and Classes 6 / 32
Objects and Classes 7 / 32
What is a Class?
Example: Dog
An attempt at a class that represents dogs:
public class Dog {
String name;
String breed;
int age;
void sleep () { ... }
void eat (String food) { ... }
String bark() { ... }
}
Mikhail Andrenkov Objects and Classes 7 / 32
Objects and Classes 8 / 32
Access Modi�ers
Access Modi�ers
Access Modi�er: Keyword written before a variable or
method that describes what entities can access it
There are four access levels:
Keyword Accessed From
public Anywhere
protected Inside the class, package, or any subclass*
no modi�er Inside the class or package
private Inside the class
* This concept will be discussed later
Mikhail Andrenkov Objects and Classes 8 / 32
Objects and Classes 9 / 32
Access Modi�ers
Access Modi�ers
Always use appropriate access modi�ers for variables and
methods
public class Dog {
public String name;
public String breed;
public int age;
public void sleep () { ... }
public void eat (String food) { ... }
public String bark() { ... }
}
Mikhail Andrenkov Objects and Classes 9 / 32
Objects and Classes 10 / 32
Class Instances
Class Instances
Objects are instances of classes
Creating an instance of a class means to instantiate that class
An object is an instantiation of a class
Mikhail Andrenkov Objects and Classes 10 / 32
Objects and Classes 11 / 32
Class Instances
Class Instances
Name: AudreyBreed: ChihuahuaAge: 2
Name: FelixBreed: German
Shepherd
Age: 5
Name: SnowBreed: HuskyAge: 3
Mikhail Andrenkov Objects and Classes 11 / 32
Objects and Classes 12 / 32
Class Constructors
What is a Constructor?
Constructor: Constructs an instance (which is an object) of aclass
Class method with no visible* return type with the same nameas the class:
class ClassName {
public ClassName ( ... ) { ... }
}
When a constructor is called, su�cient memory is allocated at
runtime to store the class
If no constructor is declared, there is a default constructor that
initializes all references to null and all primitives to their
default value
* Technically, at the JVM level, it has a void return type but this is hidden from Java programmers
Mikhail Andrenkov Objects and Classes 12 / 32
Objects and Classes 13 / 32
Class Constructors
Example: Dog
Sample constructors for the Dog class:
public class Dog {
...
public Dog () {}
public Dog (String breed , int age , String name) {
this.breed = breed;
this.name = name;
this.age = age;
}
...
}
Mikhail Andrenkov Objects and Classes 13 / 32
Objects and Classes 14 / 32
Class Constructors
Building an Object
In order to create an object that can used, it must be declaredcorrectly. What will be the result of each the followingdeclarations?
1 Dog d;
2 Dog d = new Dog();
3 Dog d = new Dog("Husky", 3, "Snow");
Mikhail Andrenkov Objects and Classes 14 / 32
Objects and Classes 15 / 32
Class Constructors
Building an Object
1 Dog d;
d •
2 Dog d = new Dog();
d Dog age 0 breed • name •
3 Dog d = new Dog("Husky", 3, "Snow");
d Dog age 3 breed • name •
"Husky" "Snow"
Mikhail Andrenkov Objects and Classes 15 / 32
Objects and Classes 16 / 32
Object References
Object References
What happens when a new value is assigned to an existing
variable?
Dog d = new Dog("German Shephard", 5, "Felix");
d = new Dog("Chihuahua", 2, "Audrey");
Mikhail Andrenkov Objects and Classes 16 / 32
Objects and Classes 17 / 32
Object References
Object References
Before:
d Dog age 5 breed • name •
"German Shepherd" "Felix"
After:
d
Dog age 5 breed • name •
"German Shepherd" "Felix"
Dog age 2 breed • name •
"Chihuahua" "Audrey"
Mikhail Andrenkov Objects and Classes 17 / 32
Objects and Classes 18 / 32
Static vs. Dynamic
Static vs. Dynamic
Dynamic methods and �elds belong to an object
Static methods and �elds belong to the class
Declarations are dynamic by default
Static declarations are labeled with the static keyword
Note: Static methods and �elds cannot reference dynamic
methods and �elds
Mikhail Andrenkov Objects and Classes 18 / 32
Objects and Classes 19 / 32
Static vs. Dynamic
Example: Dog
The scienti�c (binomial) name of a dog does not depend on
the breed, age, or name of a particular dog
It should be static:
public static final String SCIENTIFIC_NAME
= "Canis Familiaris";
public static String getScientificName () {
return "Canis Familiaris";
}
Mikhail Andrenkov Objects and Classes 19 / 32
Objects and Classes 20 / 32
Object Inheritance
What is Inheritance?
An important principle in OOP is that certain classes are
extensions of other classes
A class which extends another class's capabilities is said toinherit from that class. If X inherits from Y ...
X is a subclass of YY is a superclass of X
Every class can inherit from at most one other class
Note: All classes also inherit from Object
Mikhail Andrenkov Objects and Classes 20 / 32
Objects and Classes 21 / 32
Object Inheritance
Inheritance: Example 1
Using inheritance, commonName and scientificName do not need to
be rede�ned in each subclass:
public class Animal {
String commonName;
String scientificName;
...
}
public class Bird extends Animal {
float wingSpan;
boolean flies;
...
}
public class Fish extends Animal {
float maximumDepth;
...
}
Mikhail Andrenkov Objects and Classes 21 / 32
Objects and Classes 22 / 32
Object Inheritance
Abstract Classes
Sometimes, the base class cannot meaningfully implement a
desired method. For example:
public class Polygon {
public float perimeter () { ??? }
public float area() { ??? }
}
Abstract methods are pre�xed with the abstract keyword; they
are a �contract� that all subclasses must ful�ll
Abstract methods must be implemented by all subclasses
Abstract Class: Class with one or more abstract methodsAbstract classes cannot be instantiated
Interface: Reference type (similar to class) consisting of only
abstract methods and constants
Mikhail Andrenkov Objects and Classes 22 / 32
Objects and Classes 23 / 32
Object Inheritance
Abstract Classes: Example 1
public abstract class Polygon {
public abstract float perimeter ();
public abstract float area();
}
public class Square extends Polygon {
float side;
public float perimetre () { return side *4; }
public float area() { return side*side; }
}
public class Triangle extends Polygon {
float side0 , side1 , side2;
public float perimeter ()
{ return side0 + side1 + side2; }
public float area() { ... }
}
Mikhail Andrenkov Objects and Classes 23 / 32
Objects and Classes 24 / 32
Object Inheritance
Abstract Classes: Example 2
Abstract classes can extend other abstract classes
abstract class Quad extends Polygon {
public abstract float getSide(int n);
public float perimeter ()
{ return getSide (0) + getSide (1) + getSide (2) ←↩+ getSide (3); }
}
public class Square extends Quad {
float side;
public float getSide(int n) { return side; }
// Optional!
public float perimeter () { return side *4; }
public float area() { return side*side; }
}
Note: Since Quad implements perimeter(), Square does not
have to implement it again
Mikhail Andrenkov Objects and Classes 24 / 32
Objects and Classes 25 / 32
Object Inheritance
Final Members
Sometimes, a class may choose to implement a method where
all subclasses should have the same implementation
For example, consider this additional method:
public abstract class Polygon {
...
public int numSides () { return 4; }
}
All quadrilaterals have four sides. To ensure no subclass of
Quad can change this implementation, the implementation of
numSides() is labeled with final:
abstract class Quad extends Polygon {
...
public final int numSides () { return 4; }
}
Mikhail Andrenkov Objects and Classes 25 / 32
Objects and Classes 26 / 32
Reference vs. Object Equality
An Experiment...
The following code outputs �Equality!�:
int x = 5;
int y = 5;
if (x == y)
System.out.println("Equality!");
However, the next code segment outputs...nothing:
String x = new String("COMPSCI");
String y = new String("COMPSCI");
if (x == y)
System.out.println("Equality!");
Mikhail Andrenkov Objects and Classes 26 / 32
Objects and Classes 27 / 32
Reference vs. Object Equality
Reference vs. Object Equality
This occurs because== tests reference equality; it checks if two
references point to the same instance of an object
The following code outputs �Equality!�:
String x = new String("COMPSCI");
String y = new String("COMPSCI");
if (x.equals(y))
System.out.println("Equality!");
Object equality and reference equality are the same for
primitive types (since they are not references)
Mikhail Andrenkov Objects and Classes 27 / 32
Objects and Classes 28 / 32
Overriding
Overriding
Overriding: Providing an implementation of a method that is
already implemented in a superclass
An optional @Override annotation is placed above a methoddeclaration to indicate that it is overriding a parent class'smethod
The annotation simply informs the compiler that the followingmethod should override another methodIf the annotated method does not override another method,the compiler displays an error
Mikhail Andrenkov Objects and Classes 28 / 32
Objects and Classes 29 / 32
Overriding
Overriding: Example 1
@Override
public boolean equals (Object x) {
// If x does not refer to an object , it cannot be ←↩equal to anything
if (x == null) return false;
// Ensure that x is of the correct type
if (!(x instanceof Dog)) return false;
// Convert x, of type Object , to a reference of type←↩Dog
Dog dogX = (Dog) x;
return (this.name.equals(dogX.name) &&
this.breed.equals(dogX.breed) &&
this.age == dogX.age);
}
Mikhail Andrenkov Objects and Classes 29 / 32
Objects and Classes 30 / 32
Overriding
Overriding: Example 2
Hashing: The (usually irreversible) process of generating an
integer number within a desirable range based on an input
The performance of many data structures depend on e�cient
hash functions
Object implements an overridable hashCode() method
An example of a simple hash function converts all class
members to Strings, concatenates them, and then returns the
output of the String hashCode() function
public int hashCode () {
return (this.breed + this.name + this.age).←↩hashCode ();
}
Mikhail Andrenkov Objects and Classes 30 / 32
Objects and Classes 31 / 32
Enumerations
Enumerations
Enumeration: User-de�ned type with a small, �xed amount
of named elements
Enumeration de�nitions are labeled with the enum keyword
Use Case:
The original Dog class described distinct breeds using the breed
String propertySpelling mistakes and inconsistencies can complicate equalitychecking
e.g., "German Shepard" vs. "German Separd"
e.g., "German Shepard" vs. "german shepard"
Enumerations can eliminate these inconsistencies and simplifyequality checking
Mikhail Andrenkov Objects and Classes 31 / 32
Objects and Classes 32 / 32
Enumerations
Enumerations: Example
public class Dog {
public static enum Breed {
CHIHUAHUA , GERMAN_SHEPARD , HUSKY
}
...
public Breed breed;
...
public Dog (Breed breed , int age , String name) {
this.breed = breed;
this.age = age;
this.name = name;
}
}
// Dog d = new Dog(Dog.Breed.HUSKY , 3, "Snow");
Mikhail Andrenkov Objects and Classes 32 / 32