Object Oriented Programming With Java: Written by Amir Kirsh
Object Oriented Programming With Java: Written by Amir Kirsh
• Interfaces
• Nested Classes
• Enums
• Exercise
Classes and Objects
3
Accessibility Options
Example:
public class Person {
private String name;
protected java.util.Date birthDate;
String id; // default accessibility = package
public Person() {}
}
4
Static
5
The ‘this’ keyword
Example:
public class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
6
Defining constants
Example:
public class Thingy {
public final static doodad = 6; // constant
public final id; // constant variable
public Thingy(int id) {this.id = id;} // OK
// public set(int id) {this.id = id;} // error!
}
7
Agenda • All that is to know on class syntax
• Interfaces
• Nested Classes
• Enums
• Exercise
Constructors
– Constructors in Java are very similar to C++
– You can overload constructors (like any other method)
– A constructor which doesn't get any parameter
is called “empty constructor”
– You may prefer not to have a constructor at all,
in which case it is said that you have by default
an “empty constructor”
– A constructor can call another constructor
of the same class using the ‘this’ keyword
– Calling another constructor can be done only
as the first instruction of the calling constructor
9
Constructors
Example 1:
public class Person {
String name = ""; // fields can be initialized!
Date birthDate = new Date();
public Person() {} // empty constructor
public Person(String name, Date birthDate) {
this(name); // must be first instruction
this.birthDate = birthDate;
}
public Person(String name) {
this.name = name;
}
}
10
Constructors
Example 2:
public class Person {
String name = "";
Date birthDate = new Date();
public Person(String name, Date birthDate) {
this.name = name;
this.birthDate = birthDate;
}
}
Person p; // OK
p = new Person(); // not good – compilation error
11
Initializer
Example:
public class Thingy {
String s;
// the block underneath is an initializer
{ s="Hello"; }
} Usually initializer would do
a more complex job…
12
Static Initializer
Example:
public class Thingy {
static String s;
// the block underneath is a static initializer
static { s="Hello"; }
} Usually static initializer would
do a more complex job…
13
Agenda • All that is to know on class syntax
• Interfaces
• Nested Classes
• Enums
• Exercise
Inheritance
Some Terms
A class that is derived from another class is called a subclass
(also a derived class, extended class, or child class).
The class from which the subclass is derived is called a
superclass (also a base class or a parent class).
Excepting java.lang.Object, which has no superclass,
every class has exactly one and only one direct superclass
(single inheritance).
In the absence of any other explicit superclass, every class is
implicitly a subclass of Object.
A class is said to be descended from all the classes in its
inheritance chain stretching back to Object.
15
Inheritance
– Class Object is the ancestor base class of all classes in Java
– There is no multiple inheritance in Java
– Inheritance is always “public” thus type is not stated
(no private or protected inheritance as in C++)
– Class can implement several interfaces (contracts)
– Class can be abstract
– Access to base class is done using the super keyword
– Constructor may send parameters to its base using the
‘super’ keyword as its first instruction
– If the base class does not have an empty constructor then
the class is required to pass parameters to its super
16
Inheritance
Example 1:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
// Override toString in class Object
public String toString() {
return name;
}
}
17
Inheritance
Example 1 (cont’):
public class Employee extends Person {
private Employee manager;
public Employee(String name, Employee manager) {
super(name); // must be first
this.manager = manager;
}
// Override toString in class Person
public String toString() {
return super.toString() +
(manager!=null? ", reporting to: " + manager :
" - I'm the big boss!");
}
}
18
Inheritance
Example 2:
abstract public class Shape {
// private Color line = Color.Black;
// private Color fill = Color.White;
public Shape() {}
/* public Shape(Color line, Color fill) {
this.line = line;
this.fill = fill;
} */
abstract public void draw();
abstract public boolean isPointInside(Point p);
}
19
Inheritance
Example 2 (cont’):
public class Circle extends Shape {
private Point center;
private double radius;
public Circle(Point center, double radius) {
this.center = center; this.radius = radius;
}
public void draw() {…} // use Graphics or Graphics2d
public boolean isPointInside(Point p) {
return (p.distance(center) < radius);
}
}
20
Inheritance
The final keyword is used to forbid a method from being
override in derived classes
Above is relevant when implementing a generic algorithm in the
base class, and it allows the JVM to linkage the calls to the
method more efficiently
The final keyword can also be used on a class to prevent the
class from being subclassed at all
21
Agenda • All that is to know on class syntax
• Interfaces
• Nested Classes
• Enums
• Exercise
Interfaces
– Interface is a contract
– An interface can contain method signatures
(methods without implementation) and static constants
– Interface cannot be instantiated, it can only be implemented
by classes and extended by other interfaces
– Interface that do not include any method signature is called
a marker interface
– Class can implement several interfaces (contracts)
– Class can announce on implementing an interface,
without really implementing all of the declared methods,
but then the class must be abstract
23
Interfaces
Example 1 – using interface Comparable:
// a generic max function
static public Object max(Comparable... comparables) {
int length = comparables.length;
if(length == 0) { return null; }
Comparable max = comparables[0];
for(int i=1; i<length; i++) {
if(max.compareTo(comparables[i]) < 0) {
max = comparables[i];
}
}
return max;
}
24
Interfaces
Example 2 – supporting foreach on our own type:
To have your own class support iterating, using the "foreach“
syntax, the class should implement the interface Iterable:
25
Interfaces
Example 3 – supporting clone on our own type:
To have your own class support the clone method
the class should implement the marker interface Cloneable:
Exercise:
Implement clone for class Person
26
Interfaces
Example 4 – new IHaveName interface:
To allow name investigation we want to create a new IHaveName
interface:
Exercise:
Create the IHaveName interface and
let class Person implement it
27
Agenda • All that is to know on class syntax
• Interfaces
• Nested Classes
• Enums
• Exercise
Nested Classes
Nested Classes are divided into two categories:
static and non-static.
Nested classes that are declared static are simply called
static nested classes
Non-static nested classes are called inner classes
Inner classes that are defined without having their own name
are called anonymous classes
29
Nested Classes
Example 1:
public class OuterClass {
private int a;
static public class InnerStaticClass {
public int b;
}
public class InnerClass {
public void setA(int a1) {
a = a1; // we have access to a !!!
}
}
}
30
Nested Classes
Example 1 (cont’):
OuterClass.InnerStaticClass obj1 =
new OuterClass.InnerStaticClass();
OuterClass.InnerClass obj2 =
new OuterClass().new InnerClass();
obj2.setA(3); // we modify a of OuterClass!!!
31
Nested Classes
32
Agenda • All that is to know on class syntax
• Interfaces
• Nested Classes
• Enums
• Exercise
Enums
34
Enums
Example 1:
public class Card {
public enum Rank {
DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE,
TEN, JACK, QUEEN, KING, ACE
}
Example 1 (cont’):
public class Card {
…
public String toString() { return rank + " of " + suit; }
private static final List<Card> _deck =
new ArrayList<Card>();
// Initialize the static deck
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
_deck.add(new Card(rank, suit));
}
public static ArrayList<Card> newDeck() {
// Return copy of prototype deck
return new ArrayList<Card>(_deck);
}
}
36
Enums
Example 2:
public enum Operation {
PLUS, MINUS, TIMES, DIVIDE;
37
Enums
Example 3:
public enum Operation {
PLUS {
double eval(double x, double y) { return x + y; }
},
MINUS {
double eval(double x, double y) { return x - y; }
},
TIMES {
double eval(double x, double y) { return x * y; }
},
DIVIDE {
double eval(double x, double y) { return x / y; }
};
• Interfaces
• Nested Classes
• Enums
• Exercise
Exercise 1
Example
Rectangle A: 1 1 10 10 (which means: x1=1, y1=1, x2=10, y2=10)
Rectangle B: 5 5 10 10 (which means: x1=5, y1=5, x2=10, y2=10)
40
Exercise 2
41
That concludes this chapter
amirk at mta ac il
42