Вы находитесь на странице: 1из 29

Object-Oriented Programming

using Java

Simon Kroly
simon.karoly@codespring.ro
Classes and Objects

ADT (Abstract Data Types): data + (related) operations


encapsulation
Classes: ADT + information hiding, inheritance, polymorphism
OO principles
Object: an instance of a class
data (attributes) + operations (methods)
Object's state: determined by the current value of the attributes
References: used for identifying/accessing objects

7/11/2016 OOP in Java 2


Classes and Objects

Communication: client-server model

an operation is requested by the client


practically this request is done by calling a server method
the client object must have a reference to the server object

public class Server { public class Client {


Server s;
}
}

7/11/2016 OOP in Java 3


Classes and Objects

public class Person {


Person
//attributes:
+name: String
public String name;
+age: int
public int age;
+Person(n: String, a: int)
+learn(): void
//constructor:
+talk(): void
public Person(String n, int a) {
name = n;
p1 : Person p2 : Person
age = a;
} name = Jancsi name = Juliska
age = 18 age = 18

//methods
public void talk() {} Instantiation:
public void learn() {} Person p1 = new Person (Jancsi, 18);
Person p2 = new Person(Juliska, 18);
}

7/11/2016 OOP in Java 4


Relationships Between Classes
Association
unidirectional, bidirectional
Aggregation (weak) Car Driver

Composition (strong) drives


Cardinality:
one to one Professor Student
one to many communicates
many to many
Box Gift Dog Head
*

Student *
Town Country Capital

1..* 1 1 1

Man marriage Woman Student 10..100 1 Course

0..1 0..1

7/11/2016 OOP in Java 5


Inheritance

Person

+name: String
+age: int

+talk(): void
+learn(): void

Student Professor

+year: int +department: String

+learn(): void +talk(): void

7/11/2016 OOP in Java 6


Inheritance

Method overloading vs. method overriding


Method overloading: multiple methods within the same class
with the same method names. The parameter list is different, A

the return type may be also different. Static binding the


address of the method is known at compile phase.
B C
Method overriding: methods are redefined by the subclasses
(new specific implementation in the child class for a method that
is already provided by the superclass). Dynamic binding. D

There is no multiple inheritance in Java (and there is no


diamond inheritance problem)

7/11/2016 OOP in Java 7


Inheritance
class A {
A(String a) {
System.out.println("Constructor A " + a);
}
}

class B extends A {
B(String b) {
super(b);
System.out.println("Constructor B " + b);
}
}

public class Example {


public static void main(String[] args) {
B b = new B("Hi");
}
}

Calling a superclass constructor with parameters: super()


Super reference: referencing the instance of the superclass

7/11/2016 OOP in Java 8


Basic concepts

Constructors
Access modifiers, visibility settings for attributes and methods:
public (+) can be accessed from the class and any other classes
private (-) can only be accessed within the class
protected (#) can only be accessed within the class and its subclasses
package-private: - can be accessed from the class and from other classes
within the same package. This is the default visibility (if there are no access
modifier specified)
this reference: reference to the current object

7/11/2016 OOP in Java 9


Type modifiers

For classes:
final can not be used as a superclass
abstract can not be instantiated, can only be used as a superclass. If there
is an abstract method within a class, then the class itself must be declared
abstract.
For methods:
static class methods, there is no need for instantiation to call these
methods. They can be called using the class name: Classname.method() (e.g.
Integer.toString()). Only static attributes can be used and static methods can
be called within these methods.
abstract can be used only in abstract classes. There is no implementation
provided for these methods in the abstract class. Implementations must be
provided by the derived classes (subclasses) (or they have to be also declared
abstract).
final these methods cannot be overridden in the subclasses
native implementation is done using a native programming language
synchronized synchronized access to critical resources (see: threads)
7/11/2016 OOP in Java 10
Type modifiers

For fields:
static class attribute, the value is shared between instances (the same
value is used).
final there is only one possibility for using assignment operator (only one
value can be assigned to these attributes). The modifier is used for declaring
constants. Attention: a final reference can not be "redirected", but the object
state can be modified through the reference.
transient it is not a part of the persistent state of the object, it will be
excluded during serialization.
volatile it can be modified by multiple threads. It will be never cached
thread-locally (reads and writes are done directly to/from memory).
("synchronized" access)

7/11/2016 OOP in Java 11


Conventions
The proper form of the Person class:
public class Person {

private String name;


private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}
Naming and coding conventions
public void setName(String name) {
Private fields, public getter/setter methods
this.name = name; Suggestion: final type modifiers for constructor
} and setter parameters
public String getName() { Initializer blocks and constructors
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}

7/11/2016 OOP in Java 12


Polymorphism

Polymorphism: an object of type B behaves as an object of type A,


it is used as an object of type A. This is possible only if there is
inheritance between the corresponding classes (B is derived from A)
All of the superclass properties are inherited by the subclass, in this
way a superclass instance can be always substituted by a subclass
instance. We can say: B is A. (Attention: the inverse statement is
false.)
A simple example: the Square class (B) is derived from the Quadrangle (A) class. A
square is a quadrilateral, but not all quadrilaterals are squares. A square always
can be used as a quadrilateral, a square object can be referenced by a quadrangle
reference. Subclasses can define specific new properties, they cannot be
substituted by superclass instances (without these properties).

7/11/2016 OOP in Java 13


Polymorphism

The type used in the reference declaration vs. the type of the
referenced object.
What happens when a reference declared as type A references an
object of type B and a method is called through this reference,
which is overridden in class B? (which "version" will be actually
called?)
Probably, if the method is overridden, we want to use the implementation corresponding to the
concrete object type. This behavior is not automatically guaranteed by all programming
languages. E.g. C++ virtual methods.
In Java always the implementation corresponding to the concrete
object is called (dynamic binding). We can say: in Java all methods
are virtual.

7/11/2016 OOP in Java 14


Abstract classes

Inheritance and polymorphism a common base can be created


for different objects with common properties. When only these
common properties are relevant, the objects can be referenced in
the same way (using the common base class).
In certain situations the base class cannot be instantiated. From the
viewpoint of the system the instantiation can be senseless.
E.g.: we are creating a graphical user interface for visualizing geometric
shapes. These shapes have common properties (e.g. position, color etc.), so it
is a good idea to use a common base class for them. In this way common
properties can be inherited from this class, and in certain situations
polymorphic processing can be used (e.g. refreshing all shapes on the
interface). However, we cannot draw a shape based only on these common
properties. The direct instantiation from the base class is senseless.

7/11/2016 OOP in Java 15


Abstract classes

Abstract base classes are used to define a common interface, a


common behavior for the subclasses.
Abstract methods and classes: the abstract keyword is used for
declaring abstract methods. No implementation is provided for these
methods in the base class. If a class has an abstract method, it
must be declared abstract (by using the same abstract keyword for
the class).
Generally, abstract methods will be implemented by the subclasses.
If a subclass does not provide an implementation for an inherited
abstract method, that class must be also declared abstract.

7/11/2016 OOP in Java 16


Interfaces

The general interface notion in the context of inter-system


communication: defining access possibility to a system (a common
"boundary" between systems).
Class interfaces (general notion): public fields and methods.
Java interfaces: in Java an interface is a type declaration, defining a
given behavior. It can contain only constants and method declarations,
without implementation (method signatures). (+ also default and static
methods from Java SE 8)
If an interface is implemented by a class it is mandatory for that
class to implement all the methods declared in the interface.

7/11/2016 OOP in Java 17


Interfaces

In fact, an interface is a contract. If it is implemented by a class, that


class assumes the behavior determined by the interface.
Observation: an interface can be considered a contract, but this means only
that its methods can be called using a reference to an instance of a class
implementing that interface. It says nothing about the concrete
implementation. E.g. it is possible that a method body remains empty or an
exception is thrown by the method (e.g. OperationNotSupportedException).
Interfaces are used to create a common base for classes with common
properties (common behavior) and for avoiding unnecessary strict
dependencies.
Multiple interfaces can be implemented by the same class (difference
between interfaces and abstract classes).
As opposed to interfaces, an abstract class can contain fields and non-
abstract methods (inherited by the subclasses). In fact, all interface
methods are abstract.
7/11/2016 OOP in Java 18
Interfaces
Interface:
public interface Resizable {
public void resize(Dimension d);
}

Implementing class:
public class Circle implements Resizable {
public void resize(Dimension d) {
//source code for resizing the circle

}
}

Main:
public static void main(String[] args) {
Circle c = new Circle();
c.resize(new Dimension(100,100));
Resizable s = new Circle();
s.resize(new Dimension(100,100));
}

7/11/2016 OOP in Java 19


Interfaces

There can be inheritance between interfaces, an interface can be


extended by other interfaces. In this case multiple inheritance is
also allowed.
E.g.: we have classes implementing an interface. We want to extend the
interface with a method. In this situation all implementations have to be
changed (extended with that method). A new interface extending the first one
could be a better solution. (Observation: from Java SE 8 default methods can
be also used in similar situations.)
All interface methods are public by default (the public keyword is
optional).

7/11/2016 OOP in Java 20


Interfaces

Interfaces are often used to avoid unnecessary dependencies


E.g.: a method waits for a list of strings and writes its elements to the console.
The list can be implemented using a string array or a linked list. The concrete
implementation is irrelevant in this situation: we only need an iterator to iterate
through that list for retrieving elements. It is unnecessary (and contra-
indicated) to obligate the caller side (the code using our method) to use a given
implementation. Solution: the parameter type is declared using an interface
(instead of a class).
Other example: API (Application Programming Interface) a development team
uses a complex software package provided by another team. Typically, the
classes from the package will implement some public interfaces and will be
accessed through these interfaces. In this way, the package can be used
without knowledge related to implementation details.
Component-based programming, service-oriented architectures

7/11/2016 OOP in Java 21


Nested classes

Inner class (non-static nested class):

class A {
A(){}
class B { declaring classes within other
B() {} classes
public void doIt() { non-static nested classes
System.out.println("Hello");
}
cannot contain static methods
}; the instantiation of non-static
} nested classes is always
preceded by the instantiation of
public class Example { the outer class
public static void main(String[] args) {
A a = new A();
A.B b = a. new B();
b.doIt();

}
}

7/11/2016 OOP in Java 22


Nested classes

Static nested classes:


class A {
A() {}
static class B {
B() {}
public static void doIt() {
System.out.println("Hello");
}
};
}

public class Example{


public static void main(String[] args) {
A.B.doIt();
}
}

7/11/2016 OOP in Java 23


Nested classes

Anonymous inner classes:

...
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
...

7/11/2016 OOP in Java 24


The Object class

getClass(): returns the runtime class of this object (a Class object will
be returned).
toString(): returns a string representation for this object. By default a
string is returned based on the name of the class and the hash code of
the object. It is recommended for all subclasses to override this method.
finalize(): called by the garbage collector on an object when garbage
collection determines that there are no more references to the object. A
subclass overrides the finalize method to dispose of system resources or
to perform other cleanup.

7/11/2016 OOP in Java 25


The Object class

equals(): indicates whether some other object is "equal to" this one. For any
non-null reference values the default implementation returns true if these refer
to the same object. This method is usually overridden within subclasses to
implement an equivalence relation based on object states. E.g. two strings are
equals if they have the same content. Obs.: it is generally necessary to override
the hashCode method whenever the equals method is overridden (see the
general contract of the hashCode method).
hashCode(): returns an integer, the hash code value for the object. This
method is supported for the benefit of hash tables. The default implementation
returns distinct integers for distinct objects (typically implemented by using the
internal address of the object). If two objects are equal according to the equals
method, then calling the hashCode method the same integer result has to be
produced for both objects. (Generally, all the fields used for equality check
within the equals method will be used for generating the hash code.)

7/11/2016 OOP in Java 26


The Object class

clone(): creates and returns a copy of this object. The signature of the
method:
protected Object clone() throws CloneNotSupportedException
A copy can be created only if the Cloneable interface is implemented by the class
(otherwise runtime exception is thrown). This interface is not implemented by the
Object class, so not all Java objects are cloneable.
The clone method creates a new instance of the class of this object and initializes
all its fields with the contents of the corresponding fields of this object. By default,
the contents of the fields are not themselves cloned. Thus, by default the method
performs a shallow copy. It should be properly overridden to perform a deep copy.

wait(), notify(), notifyAll() see threads/synchronization (will be


discussed later)

7/11/2016 OOP in Java 27


Packages
A group of classes and interfaces
jar archiver
Creating packages:
package MyPackage;
public class MyBaseClass {
...
}
package MyPackage;
public class MyDerivedClass extends MyBaseClass {
...
}

Using packages:
java.awt.Button b;
MyPackage.MyBaseClass ob;
MyPackage.MyDerivedClass od;
or:
import java.awt.Button;
import MyPackage.MyBaseClass;
import MyPackage.MyDerivedClass
or:
import java.awt.*;
import MyPackage.*;

7/11/2016 OOP in Java 28


Example

core collection

Person
StudentIterator
#name: String
#age: int +hasMoreElements(): boolean
+nextElement(): Student
+Person(String, int)
+getName(): String
+setName(String): void <<inner class>>
+getAge(): int StudentIteratorImpl
+setAge(int): void
-index: int

+StudentIteratorImpl()
Student +hasMoreElements(): boolean
+nextElement(): Student
-faculty: String

+Student(String, int, String) StudentList


+getFaculty(): String
+setFaculty(String): void * -current: int
+toString(): String -students: array of Student

+StudentList(int size)
+addStudent(Student): void
TestStudentList
+getIterator(): StudentIterator

+main(String[] args): static void

7/11/2016 OOP in Java 29

Вам также может понравиться