CSC 308 2.0
System Development with Java
Object Oriented Programming with Java Budditha Hettige Department of Statistics and Computer Science Budditha Hettige
1
Advantages of OOP • Provides a clear modular structure for programs • OOP makes it easy to maintain and modify existing code (new objects can be created with small differences to existing ones) • OOP provides a good framework for code libraries • Software components can be easily adapted and modified by the programmer.
Budditha Hettige
2
Concepts of OOP • • • • • •
Objects Classes Data Abstraction Encapsulation Inheritance Polymorphism
Budditha Hettige
3
What is an Objects? • Object is a software bundle of related state and behavior • Characteristics: – state and behavior
Budditha Hettige
4
What is a class? • A Java class is a group of Java methods and variables • Object is an instance of a class
Budditha Hettige
5
Object Oriented Concepts
Budditha Hettige
6
Constructors • Very similar to C++ • You can create multiple constructors, each must accept different parameters. • If you don't write any constructor, the compiler will (in effect) write one for you: classname() {}
• If you include any constructors in a class, the compiler will not create a default constructor!
Budditha Hettige
7
Multiple Constructors • One constructor can call another. • You use "this", not the classname: class Foo { int i; Foo() { this(0); } Foo( int x ) { i = x; }
A call to this must be the first statement in the constructor!
Budditha Hettige
8
Destructors • No! • There is a finalize() method that is called when an object is destroyed. – you don't have control over when the object is destroyed (it might never be destroyed). – The JVM garbage collector takes care of destroying objects automatically (you have limited control over this process).
Budditha Hettige
9
Class Modifiers • • • •
Public Abstract Final Default (none)
Budditha Hettige
10
Class Modifiers • public: anyone can create an object of the
defined class. – only one public class per file, must have same name as the file (this is how Java finds it!).
• default: is non-public (if you don't specify "public").
Budditha Hettige
11
Class Modifiers • Abstract: modifier means that the class can be used as a superclass only. – no objects of this class can be created.
• Final: if its definition is complete and no subclasses are desired or required – a final class never has any subclasses, the methods of a final class are never overridden Budditha Hettige
12
Field Modifiers • • • • • •
public protected private none or package or default Static Final
Budditha Hettige
13
Field Modifiers • public: any method (in any class) can access the
field. • protected: any method in the same package can
access the field, or any derived class. • private: only methods in the class can access the field. • Default: is that only methods in the same package can access the field.
Budditha Hettige
14
Field Modifiers • Static: Fields declared static are called class fields (class variables). others are called instance fields. There is only one copy of a static field, no matter how many objects are created. • Final:class and instance variables (static and non-static fields) may be declared final. The keyword final means: once the value is set, it can never be changed – static final int BUFSIZE=100; – final double PI=3.14159; Budditha Hettige
15
Method Modifiers • • • • • • • • •
public protected none or package or default private final abstract static native synchronized Budditha Hettige
16
Method Modifiers • private/protected/public: – same idea as with fields. • abstract: no implementation given, must be
supplied by subclass. – the class itself must also be declared abstract
Budditha Hettige
17
Method Modifiers • static: the method is a class method, it
doesn't depend on any instance fields or methods, and can be called without first creating an object. • final: the method cannot be changed by a subclass (no alternative implementation can be provided by a subclass). Budditha Hettige
18
Method Modifiers • native: the method is written in some
local code (C/C++) - the implementation is not provided in Java. • synchronized: only one thread at a time
can call the method.
Budditha Hettige
19
Method Overloading • You can overload methods: – same method name, different parameters. – you can't just change return type, the parameters need to be different.
• Method overloading is resolved at compile time. int CounterValue() { return counter;
}
Won't Work!
double CounterValue() { return (double) counter; } Budditha Hettige
20
All Possible Combinations of Features and Modifiers Modifier public protected None (default)
Class yes no yes
Variable yes yes yes
Method yes yes yes
Constructor yes yes yes
private final abstract static native transient volatile synchronized strictfp
no yes yes no no no no no yes
yes yes no yes no yes yes no no
yes yes yes yes yes no no yes yes
yes no no no no no no no yes
Budditha Hettige
21
Java Modifier Summary
Modifier Used on Class
abstract
Meaning Contains unimplemented methods and cannot be instantiated
All interfaces are abstract. Optional in interface declarations
method No body, only signature. The enclosing class is abstract
Budditha Hettige
22
Java Modifier Summary Modifier Used on
Final
Meaning
Class
Cannot be subclassed
method
Cannot be overridden and dynamically looked up
field
Cannot change its value. static final fields are compile-time constants.
variable Cannot change its value. Budditha Hettige
23
Java Modifier Summary Modifier Used on Native method
Meaning Platform-dependent. No body, only signature
Meaning
Modifier Used on
Private member Accessible only in its class
Modifier Used on protected
member
Meaning Accessible only within its package and its subclasses
Budditha Hettige
24
Java Modifier Summary Modifier Used on Class None
Meaning Accessible only in its package
Interface Accessible only in its package Member Accessible only in its package
Budditha Hettige
25
Java Modifier Summary Modifier Used on Class
Public
Meaning Accessible anywhere
interface Accessible anywhere Member Accessible anywhere.
Budditha Hettige
26
Java Modifier Summary
static
class
Make an inner class top-level class
method
A class method, invoked through the class name.
field
initializer
A class field, invoked through the class name one instance, regardless of class instances created. Run when the class is loaded, rather than when an instance is created. Budditha Hettige
27
Packages
Budditha Hettige
28
Package • defined as a grouping of related types • existing packages in Java are: – java.lang - bundles the fundamental classes – java.io - classes for input , output functions are bundled in this package
Budditha Hettige
29
Creating a Package • Put a package statement with the package name • At the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package • The package statement should be the first line in the source file • There can be only one package statement in each source file, and it applies to all types in the file Budditha Hettige
30
Example /* File name : Animal.java */ package animals; interface Animal { public void eat(); } package animals; /* File name : MammalInt.java */ public class Mammal implements Animal { public void eat() { System.out.println("Mammal eats"); }
Now you compile these two files and put them in a sub-directory called animals Budditha Hettige
31
The Import Keyword • If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other without any special syntax • The fully qualified name of the class can be used. – import animals.Mamal
• The package can be imported using the import keyword and the wild card (*) – import animals.*; Budditha Hettige
32
Abstraction
Budditha Hettige
33
Abstraction • Refers to the ability to make a class abstract in OOP • Abstract class – Cannot be instantiated – Other functionality of the class still exists – Cannot create an instance of the abstract class
Budditha Hettige
34
Abstract Class • Use the abstract keyword to declare a class abstract public abstract class Employee { private String name; private String address; ... }
Cannot use Employee e = new Employee(); Employee.java: xx: Employee is abstract; cannot be instantiated Employee e = new Employee(); ^ 1 error1 Budditha Hettige
35
Extending Abstract Class public class Salary extends Employee { Extend Employee class private double salary; Salary(String name, String address, int number, double salary) { super(name, address, number); setSalary(salary); Call Employee } class ... } Budditha Hettige
36
Abstract Methods • Can declare the method in the parent class as abstract • Abstract methods consist of a method signature, but no method body public abstract class Employee { private String name; private String address; private int number;
public abstract double computePay(); //Remainder of class definition }
Budditha Hettige
37
Declaring a Method as Abstract • The class must also be declared abstract • Any child class must either override the abstract method or declare itself abstract – A child class that inherits an abstract method must override it – If they do not, they must be abstract,and any of their children must override it
Budditha Hettige
38
Salary is Extending Employee class • it is required to implement computePay() method public class Salary extends Employee { private double salary; //Annual salary public double computePay() { System.out.println("Computing " + getName()); return salary/52; } //Remainder of class definition }
Budditha Hettige
39
Example
Budditha Hettige
40
Example(1) Employee ------------Name Address Number computePay() mailCheck() toString() getName() …
Budditha Hettige
41
Salary class Employee
Salary
Budditha Hettige
42
Abstract Demonstration Employee
Salary
Budditha Hettige
43
Exercise • Remove computePay() methods in the Salary class and re-run the program. • Change the computePay() as public abstract double computePay() ; And re-run the program
• Identify the correct usage of the – Abstract class – Abstract methods Budditha Hettige
44
Encapsulation
Budditha Hettige
45
Encapsulation • Information Hiding. • Don't need to know how some component is implemented to use it. • Implementation can change without effecting any calling code. • "protects us from ourselves"
Budditha Hettige
46
Encapsulation • is the technique of making the fields in a class private and providing access to the fields via public methods • is also referred to as data hiding • Benefit – is the ability to modify our implemented code without breaking the code of others who use our code
• Encapsulation gives maintainability, flexibility and extensibility to our code Budditha Hettige
47
Example public class Encap { private String name; private String idNum; private int age; public int getAge() { return age; } public String getName() { return name; }
public String getIdNum() { return idNum; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setIdNum( String newId) { idNum = newId; } } Budditha Hettige
48
Example public class RunEncap { public static void main(String args[]) { EncapTest encap = new EncapTest(); encap.setName("James"); encap.setAge(20); encap.setIdNum("12343ms"); System.out.println("Name : " + encap.getName()+ " Age : "+ encap.getAge());
} }
Budditha Hettige
49
Benefits of Encapsulation: • The fields of a class can be made read-only or write-only. • A class can have total control over what is stored in its fields. • The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code. Budditha Hettige
50
Inheritance
Budditha Hettige
51
Inheritance • On the surface, inheritance is a code re-use issue. – we can extend code that is already written in a manageable manner.
• Inheritance is more, it supports polymorphism at the language level! • Information is made manageable in a hierarchical order Budditha Hettige
52
Inheritance cont. • With Inheritance, new class can be derived from existing classes as a building block • New class Inherit properties and methods from the existing class • New class can also added Its own properties and methods • Keyword – Extends – Implements Budditha Hettige
53
Inheritance cont. • Take an existing object type (collection of fields and methods) and extend it. – create a special version of the code without rewriting any of the existing code (or even explicitly calling it!). – End result is a more specific object type, called the sub-class / derived class / child class. – The original code is called the super class / parent class / base class.
Budditha Hettige
54
IS-A Relationship (Example) public class Animal { }
Animal
extends
public class Mammal extends Animal { } Mamal
public class Reptile extends Animal { } public class Dog extends Mammal { } Budditha Hettige
55
IS-A Relationship (Example) public class Dog extends Mammal { public static void main(String args[]) { Animal a = new Animal(); Reptile r = new Reptile(); Mamal Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } } Budditha Hettige
Animal
Dog
Reptile
56
IS-A Relationship • In Object Oriented terms following are true: – Animal is the superclass of Mammal class. – Animal is the superclass of Reptile class. – Mammal and Reptile are sub classes of Animal class. – Dog is the subclass of both Mammal and Animal classes.
Budditha Hettige
57
IS-A Relationship • IS-A relationship we can say: – Mammal IS-A Animal – Reptile IS-A Animal – Dog IS-A Mammal – Hence : Dog IS-A Animal as well
• Use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass Budditha Hettige
58
Accessing superclass methods • Can use super() to access all (non-private) superclass methods. – even those replaced with new versions in the derived class.
• Can use super() to call base class constructor.
Budditha Hettige
59
Single Inheritance • You can't extend more than one class! – the derived class can't have more than one base class.
• You can do multiple inheritance with interface inheritance.
Budditha Hettige
60
Inheritance Example cont. • Employee: name, email, phone – FulltimeEmployee: also has salary, office, benefits, … • Manager: CompanyCar, can change salaries, rates contracts, offices, etc.
– Contractor: HourlyRate, ContractDuration, …
• A manager a special kind of FullTimeEmployee, which is a special kind of Employee. • The relationship modeled by inheritance is often referred to as a “is a” relationship Budditha Hettige
61
Inheritance Example Employee -----------------Name Email Phone
FulltimeEmployee -----------------------Salary Office
Contractor -----------------HourlyRate, ContractDuration
Manager -----------------CompanyCar Email Phone Budditha Hettige
62
Inheritance Example Is a
Employee -----------------Name Email Phone
Is a
FulltimeEmployee -----------------------Salary Office
Is a Manager -----------------CompanyCar Email Phone Budditha Hettige
Contractor -----------------HourlyRate, ContractDuration
63
Inheritance Example • Manager is a full time employee • Full time employee is a employee
Budditha Hettige
64
HAS-A Relationship • relationships are mainly based on the usage • determines whether a certain class HAS-A certain thing • helps to reduce duplication of code as well as bugs
Budditha Hettige
65
Example public class Vehicle {} public class Speed {} public class Van extends Vehicle { private Speed sp; } • class Van HAS-A Speed
Vehicle
Van sp
– Reuse the Speed class in multiple applications Budditha Hettige
66
Interface
Budditha Hettige
67
Interfaces • is a collection of abstract methods • An interface is not a class – A class describes the attributes and behaviors of an object – An interface contains behaviors that a class implements
Budditha Hettige
68
Interfaces cont. • Interfaces have the following properties: – An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface. – Methods in an interface are implicitly public.
Budditha Hettige
69
Interfaces cont. • An interface is a definition of method prototypes and possibly some constants (static final fields). • An interface does not include the implementation of any methods, it just defines a set of methods that could be implemented.
Budditha Hettige
70
Implement an interfaces • A class can implement an interface, this means that it provides implementations for all the methods in the interface. • Java classes can implement any number of interfaces (multiple interface inheritance).
Budditha Hettige
71
Interfaces • Creation (definition) of interfaces can be done using inheritance: – one interface can extend another.
• Sometimes interfaces are used just as labeling mechanisms: – Look in the Java API documentation for interfaces like Cloneable.
Budditha Hettige
72
Interfaces • An interface is similar to a class in the following ways: – An interface can contain any number of methods. – An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. – The bytecode of an interface appears in a .class file. – Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. Budditha Hettige
73
Interfaces • An interface is different from a class in several ways, including: – – – –
You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. – An interface is not extended by a class; it is implemented by a class. – An interface can extend multiple interfaces. Budditha Hettige
74
Declaring Interfaces • The interface keyword is used to declare an interface public class MammalInt implements Animal { public void eat() { System.out.println("Mammal eats"); } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); } } Budditha Hettige
interface Animal { public void eat(); }
75
Extending Interfaces • An interface can extend another interface public interface Sports { public void setHomeTeam(String name); } public interface Football extends Sports { public void homeTeamScored(int points); }
Sport
Football
Hockey
public interface Hockey extends Sports { public void homeGoalScored(); } Budditha Hettige
76
Multiple Interfaces • A Java class can only extend one parent class. • Multiple inheritance is not allowed • An interface can extend more than one parent interface • Extends keyword is used once, and the parent interfaces are declared in a comma-separated list. – public interface Hockey extends Sports, Event Sports
Event
Hockey
Budditha Hettige
77
The “instanceof” Keyword • the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal
Budditha Hettige
78
Polymorphism
Budditha Hettige
79
Polymorphism • is the ability of an object to take on many forms • OOP occurs when a parent class reference is used to refer to a child class object
Budditha Hettige
80
Polymorphism • Create code that deals with general object types, without the need to know what specific type each object is. • Generate a list of employee names: – all objects derived from Employee have a name field! – no need to treat managers differently from anyone else.
Budditha Hettige
81
Polymorphism • The real power comes with methods/behaviors. • A better example: – shape object types used by a drawing program. – we want to be able to handle any kind of shape someone wants to code (in the future). – we want to be able to write code now that can deal with shape objects (without knowing what they are!).
Budditha Hettige
82
Example public interface Vegetarian {} public class Animal{} public class Deer extends Animal implements Vegetarian{}
• Deer class is considered to be polymorphic since this has multiple inheritance
– A Deer IS-A aAnimal – A Deer IS-A Vegetarian – A Deer IS-A Deer – A Deer IS-A Object Budditha Hettige
83
Types of Polymorphism • Overloading • Overriding • Dynamic method binding
Budditha Hettige
84
Example public static void main ( String ary[ ] ) { Box x; Box b1 =new Box( ); WoddenBox wb=new WoddenBox( ); SteelBox s1=new SteelBox( ); LargeWoddenBox p1=new LargeWoddenBox( ); b1.info( ); wb.info( ); s1.info( ); p1.info( ); System.out.println("-------------------------"); Box b[]=new Box[5]; b[1]=new Box(); b[2]=new WoddenBox(); b[3]=new SteelBox(); b[4]=new LargeWoddenBox(); for(int i=1;i