Object Oriented (OO) Concepts with JAVA MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Computing Department s.stafrace@surrey.ac.uk 1
What is OO Programming? Programming paradigm How a solution to a problem is formulated in a programming language Other paradigms: procedural, functional, declarative, etc Based on objects (or classes of objects) and their relationships Fundamental OO concepts include: Encapsulation, Inheritance, Polymorphism and Abstraction Other concepts include: Method Overriding and Overloading Packages and Interfaces 2
RECAP 3
Objects and Classes (1) What is a Software Object? Conceptually similar to real world objects Contains fields (state) and methods (behaviour) Benefits of using software objects Modularity The source code of an object can be written independently of the source code of other objects Code reuse If an object already exists, you can use it in your own code Debugging ease If an object contains a bug, it can be unplugged from the system and replaced with a functioning object part replacement concept 4
Objects and Classes (2) What is a Class? A class is the blueprint from which individual objects are created In OO terms, we say that an object is an instance of a class of objects 5
Encapsulation What is Encapsulation (aka data hiding)? Hide the internal state whilst all interaction is done through the object s methods All fields are declared private Use of Getter and Setter methods Benefits of encapsulation Shields the internal state from random external access Allows for state (or field) validation Fields can be read-only or write-only Details of the internal implementation are hidden from the outside world Encapsulated fields can be modified without affecting dependant code 6
Inheritance (1) What is Inheritance? The process by which a class acquires the properties of another class Classes can inherit the state and behaviour of other classes Each class is allowed to have one superclass (aka single inheritance) and each superclass can have multiple subclasses 7
Inheritance (2) class MountainBike extends Bicycle { // New fields and methods go here The subclass MountainBike inherits all the fields and methods from class Bicycle The developer can focus on the properties that make MountainBike unique 8
Inheritance (3) Keyword instanceof Operator that can determine whether a class is the subclass of another class IS-A vs. HAS-A relationship Inheritance represents an IS-A relationship where an object is a type of another object Composition is instead a HAS-A relationship whereby a class is made up from other classes E.g. The Car class is composed of various other classes such as Engine class, Wheel class, Battery class, etc 9
Overriding an inherited method (1) A subclass can override an inherited method i.e. override the functionality of any existing method Provided it is not marked as final Why would you override a method? It gives you the ability to define a behaviour that s specific to the subclass type You can use the @Override annotation that instructs the compiler that you intend to override a method in the super class 10
Overriding an inherited method (2) class Animal{ public void move(){ System.out.println("Animals can move"); class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); public class TestDog{ public static void main(string args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//runs the method in Dog class 11
Overriding an inherited method (3) Rules for overriding The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the super class. The access level cannot be more restrictive than the overridden method's access level. Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. Constructors cannot be overridden. 12
Overriding an inherited method (4) Invoking a super class version of an overridden method Use the super reserved word class Animal{ public void move(){ System.out.println("Animals can move"); class Dog extends Animal{ public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); public class TestDog{ public static void main(string args[]){ Animal b = new Dog(); // Animal reference but Dog object b.move();//runs the method in Dog class 13
Overriding an inherited method (5) Overriding vs. Overloading Different methods with these same name but a different number of parameters for example: int add(int pvalue1, int pvalue2) double add(double pvalue1, double pvalue2) Overloading makes the code more readable Java compiler determines which method is used based on the method signature QUESTION: If a subclass overloads a super class method is it the same as overriding? 14
Polymorphism (1) What is polymorphism? From Greek origin: The ability of an object to take on many forms public class Shape { public class Circle extends Shape { public class Square extends Shape { Using the IS-A relationship A shape can be a circle or a square We use virtual method invocation to take advantage of polymorphism 15
Polymorphism (2) public class Shape { public double area(){ System.out.println( No shape defined"); return 0.0; public class Circle extends Shape{ final static double pi = 3.14; double radius; public double area(){ System.out.println( Circle area: + (pi*(radius^2)) ); return pi*(radius^2); public class Square extends Shape{ double length; public double area(){ System.out.println( Square area: + (length^2) ); return pi*(radius^2); 16
Polymorphism (3) public class TestVMI { public static void main(string[] args){ Shape shape = new Shape(); Shape circle = new Circle(); Shape square = new Square(); shape.area(); circle.area(); square.area(); Java compiler checks that the Shape object has a method called area() JVM invokes the appropriate method according to the reference type of the object instance (aka reference variable) 17
Abstraction (1) What is Abstraction? In OOP, it is the ability to make a class abstract An abstract class can contain fields, constructors and methods; however, it cannot be instantiated, but can be subclassed An abstract class can contain abstract methods i.e. methods that do not have an implementation Any child class must either override the abstract method or declare itself abstract. So what is the use of an abstract class? An abstract class can implement common functionality found in its subclasses; however still have some methods that are different and therefore not implemented. E.g. Shape vs. Circle or Square 18
Abstraction (2) In Java, we use the reserved word abstract to declare a class or a method as abstract public abstract class Shape { int x, y; public void moveto(int newx, int newy) { public abstract double area(); public abstract void draw(); public class Circle extends Shape{ final static double pi = 3.14; double radius; public double area(){ System.out.println( Circle area: + (pi*(radius^2)) ); return pi*(radius^2); 19
Abstraction (3) An abstract class may have static fields and static methods. You can use these static members with a class reference E.g. AbstractClass.staticMethod() - as you would with any other class Abstract classes vs. Interfaces What s the difference? You should tell me by the end of this tutorial 20
Interfaces (1) What is an interface? Generally, it is defined as a collection of abstract methods that define an object s interface with the outside world In Java, it is a reference type that can contain only constants, method signatures and nested types (inner classes) It is not a class, but they do share some similarities: 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 21
Understanding Interfaces (2) Interfaces vs. Classes - how are they different? 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. 22
Declaring Interfaces (3) public interface operatecar { // constant declarations, if any // method signatures int changelanes(direction direction, double startspeed, double endspeed); int signalturn(direction direction, boolean signalon);... // more method signatures To declare an interface in Java, we obviously use the keyword interface An interface is implicitly abstract Each method in an interface is also implicitly abstract Methods in an interface are implicitly public. 23
Implementing Interfaces (4) public class OperatePorsche implements OperateCar { // the OperateCar method signatures, with implementation // for example: int signalturn(direction direction, boolean signalon) { //code to turn indicator lights on A class uses the implements keyword to implement an interface The keyword appears in the class declaration following the extends portion of the declaration A class can extend only one class, but implement many interfaces Closest we get to multiple inheritance An interface can be used as a type 24
Interfaces as a Type (5) Example of using an interface as a type: public interface Relatable { // this (object calling islargerthan) and // other must be instances of the same class // returns 1, 0, -1 if this is greater // than, equal to, or less than other public int islargerthan(relatable other); public Object findlargest(object object1, Object object2) { Relatable obj1 = (Relatable)object1; Relatable obj2 = (Relatable)object2; if ( (obj1).islargerthan(obj2) > 0) return object1; else return object2; 25
Extending Interfaces (6) public interface Sports { public void sethometeam(string name); public void setvisitingteam(string name); public interface Football extends Sports { public void hometeamscored(int points); public void visitingteamscored(int points); An interface can extend another interface The extends keyword is used to extend an interface The child interface inherits the methods of the parent interface An interface can extend more than one parent interface In contrast with with the class hierarchy, where a class can extend only one class 26
Packages (1) What is a Package? A Package can be defined as a grouping of related types, such as classes and interfaces, providing access protection and name space management Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, etc easier Existing packages in Java are: java.lang - bundles the fundamental classes java.io - classes for input and output functions A programmer can create his/her own packages 27
Packages (2) Creating a new package Choose a name for the package and It is common practice to use lowercase names to avoid any conflicts with the names of classes, interfaces, etc Put a package statement with that name at the top of every source file that contains the classes and interfaces that you want to include in the package. package graphics; public abstract class Shape { public class Circle extends Shape{ 28
Packages (3) Naming a package It is likely that many programmers will use the same name for different types E.g. java.awt.circle vs. graphic.circle Fully qualified name avoids ambiguity What happens if two independent programmers use the same name for their packages? We use naming convention to avoid this situation Companies use their reversed Internet domain name to begin their package names Packages in the Java language itself begin with java. or javax Use an underscore for domain names that are invalid for package names 29
Packages (4) Using a package member The types that comprise a package are known as the package members How do use a public package member from outside its package? Refer to the member by its fully qualified name Import the package member Import the member's entire package Apparent hierarchy of packages For instance: java.awt package, java.awt.color package and java.awt.font package The java.awt.color and java.awt.font packages are NOT INCLUDED in the java.awt package 30
Packages (5) Name ambiguities If a member in one package shares its name with a member in another package and both packages are imported, you must refer to each member by its qualified name Static imports To reference a static final fields, you prefix the field with the class name E.g. Math.PI In case you need frequent access to static final fields (constants) and static methods from one or two classes Avoid cluttered code by using import static java.lang.math.pi Use static import very sparingly 31
Packages (6) The name of the package must match the directory structure where the corresponding class file (bytecode) resides E.g. graphics.circle.java should reside in Windows location C:\<project_path>\graphics (in UNIX, use a forward slash (/)) Always remember the CLASSPATH variable! To display the current CLASSPATH variable: In Windows -> C:\> set CLASSPATH In Unix -> % echo $CLASSPATH To delete the current contents of the CLASSPATH variable: In Windows -> C:\> set CLASSPATH= In Unix -> % unset CLASSPATH; export CLASSPATH To set the CLASSPATH variable: In Windows -> set CLASSPATH=C:\users\stefan\java\classes In Unix -> % CLASSPATH=/home/stefan/java/classes; export CLASSPATH 32
References SUN Java Trail Learning the Java Language http://java.sun.com/docs/books/tutorial/java/toc.html Tutorials Point - Java Tutorial http://www.tutorialspoint.com/java/index.htm 33
The End Questions? Comments? Thoughts? 34