Java OOP
Intro
- Coding paradigm of the 90s
- Many OO languages now (Java, Eiffel, SmallTalk)
- Or OO aspects (Basic, Pascal, ADA)
- Scripting langs with OO aspects (JavaScript, Python)
- Better code base, less bugs/errors
- Abstraction
- Seperation between concept and implementation
- Class - Object
- Class as blueprint
- Object as instance of a class
Encapsulation
- Class contains data and behavior
- Data given by set of class fields
- Behavior is given by set of methods
- So called class members
- Hide implementation details
- Only certain interface is visible for consumer
Relations
- "is-a" relation
- Triangle is a shape
- Generalization/Specialization
- Triangle as specialization of shape
- Shape as a generalization of a triangle
- "part-of" relation
- Bicycle consists of many parts
- In OOP given by class variable
- Aggregation/Composition
- Association
- E.g. class invokes / uses other class
- used in local contexts or in method calls
OOP Elements
- Basic elements: classes, objects, interfaces
- Classes
- set of data
- set of behavior (methods)
- Object
- instance of class
- allocated in memory
- multiple instances possible
- Class inheritance
- subclasses may inherit class members from base classes
- Class visibility (encapsulation)
- inner details should be private
- accessible data should be public (getter/setter)
Class Syntax
/*
* [javaModifiers] class className [extends someSuperClass]
* [implements someInterfaces sep by commas]
* {
* // Data members
* // Constructors
* // Methods
* }
*/
public class Candidate { // ... }
class Stats extends ToolSet { // ... }
public class Report extends ToolSet implements Runnable { // ... }
- Class signature, optional constructors, data members and methods
- Class instance (object)
- Candidate cand = new Candidate();
Class Members
/*
* [javaModifier] type dataMemberName;
* [javaModifiers] type methodName (parameterList)
* [throws listOfExceptionsSepByComas] {
* // ...
* }
*
*/
public class Candidate {
private String firstName;
private String lastName;
private int year;
public void setYear(int y) { year = y; }
public String getLastName() { return lastName; }
}
- Access data members and methods
- candidate1.setYear(2016);
- String name = getFirstName() + getLastName();
Overloading
- Methods and constructors can be overloaded
- Two or more methods have same name but different signature
- Method signature: return value, method name and parameters
- Having only different return type is not overloading
- Access methods can be different of overloaded methods
- May throw different exceptions
public class VotingMachine {
// ...
public void startUp() { // ... }
public void startUp(int delay) { // ... }
private String startUp(District d) throws new IOException { // ... }
}
Overriding
- Subclass may override methods that it inherits
- Must have same signature
- final, static or private methods cannot be overriden
- protected methods may override methods that have no access modifiers
- Overriding method cannot have more restrictive access modifiers
- May not throw any new checked exceptions
public class Display {
void startUp() {
// ...
}
}
public class TouchScreenDisplay extends Display {
void startUp() {
// ...
}
}
Constructors
- Called upon object creation
- Used to initialize data in created object
- Is optional, has same name as class
- no return statement in body
- Classes have implicit no-arg constructors
- If explicit constructor with args is added, there is no std constructor
public class Candidate {
Candidate(int id) {
this.identification = id;
}
Candidate(int id, int age) {
this.identification = id;
this.age = age;
}
}
Superclasses and Subclasses
- A class can inherit from a single base class
- Subclass inherits data members and methods
- No direct access to private members of superclass
- super keyword
- Used to access overriden methods from base class
- Use super to class constructor of superclass
- Must be first statement in constructor
public class Machine {
boolean state;
void setState(boolean s) { state = s; }
boolean getState() { return state; }
}
public class VotingMachine extends Machine { // ... }
This keyword
- Refer to current object with this keyword
- Call constructor within other constructor
- Pass reference of current object to another object
- Assign a parameter variable to instance variable
public class Curtain {
public Curtain(int length, int width) { // ... }
public Curtain() { this(10,9); }
}
public void setColor(String color) {
this.color = color;
}
Abstract Classes
- Used as base class
- Contains abstract methods
- All abstract methods must be defined by deriving class
- Otherwise derived class is also abstract
- Abstract methods just have method declaration
public abstract class Shape {
public abstract void draw();
}
public class Triangle extends Shape {
public void draw() {
// ...
}
}
Static Members
- Reside inside class, no instance needed
public class Voter {
static int count = 0;
// static constants
static final int AGE_IMIT;
static {
// init static members
AGE_IMIT = 18;
}
public Voter() { counter++; }
public static int getVoterCount() {
return count;
}
}
Interfaces
- Set of public signatures
- Class that implements interface must provide implementations
- Otherwise must be declared abstract
- Classes may implement multiple interfaces
- Interfaces may extend multiple interfaces
public interface Reportable {
void genReport(String repType);
void printReport(String repType);
}
public abstract class A implements Reportable {
// ...
}
Polymorphism
- Variables may hold objects of different classes
- Variable of type X can hold objects of type X or derived objects
- Late binding: decide during run-time which method to call
public abstract class Shape {
public abstract void draw();
}
public class Triangle extends Shape { // ... }
public class Rectangle extends Shape { // ... }
public class Circle extends Shape { // ... }
public class Main {
public static void main(String[] args){
ArrayList<Shape> myShapes = new ArrayList<Shape>();
myShapes.add(new Circle());
myShapes.add(new Triangle());
myShapes.add(new Rectangle());
for(int ii = 0; ii < myShapes.size(); ii++) {
myShapes.get(ii).draw();
}
}
}
Enumerations
- Set of object that represent related set of choices
- enum is a class of type enum and it is singleton
- enum classes can have methods, constructors and members
enum DisplayButton {
ROUND (.50f),
SQUARE (.40f);
private final float size;
DisplayButton(float size) { this.size = size; }
private float size() { return size; }
}
DisplayButton round = DisplayButton.ROUND;
Annotation Types
- Associate metadata with program elements at compile/run-time
- Packages, classes, methods, fields, parameters, variables, constructors can be annotated
- Built-in annotations
- @Override, @Deprecated, @SuppressWarnings
- Must be placed before the annotated item
// @Override is a marker annotation
// compile warning will be returned if method cannot be found
@Override public String toString() { // ... }
Developer-Defined Annotations
- Devs may define own annotations
- 3 annotation types
- Marker annotation has no params
- Single value annotation has single param
- Multi value annotation has multiple params
// @interface annotationName { ... } // defines annotation
public @interface Feedback {
String reportName();
String comment default "None";
}
@Feedbaack(reportName="Report 1")
public void myMethod() { // ... }
References
Handbuch der Java-Programmierung
(5. Auflage)
Thank you for your attention!
Java OOP
By dinony
Java OOP
- 371