Chapter_7-ObjectOrientedFeatures.pdf
Document Details
Related
- PCSII Depression/Anxiety/Strong Emotions 2024 Document
- A Concise History of the World: A New World of Connections (1500-1800)
- Human Bio Test PDF
- Vertebrate Pest Management PDF
- Lg 5 International Environmental Laws, Treaties, Protocols, and Conventions
- Fármacos Anticoncepcionais e Disfunção Erétil PDF
Full Transcript
7 Basic Features of Object Oriented Programming 1. Abstraction 2. Encapsulation 3. Inheritance 4. Polymorphism 7.1. Abstraction Abstraction is the concept of exposing only the required essential characteristics and behaviours with respect to a context (proble...
7 Basic Features of Object Oriented Programming 1. Abstraction 2. Encapsulation 3. Inheritance 4. Polymorphism 7.1. Abstraction Abstraction is the concept of exposing only the required essential characteristics and behaviours with respect to a context (problem domain). When you change your vehicle's gear, are you concerned about the inner details of your vehicle engine? No, but what matters to you is that Gear must get changed that’s it! This is abstraction; show only the details which matter to the user. In Java abstraction is achieved using interfaces and abstract classes. 7.2. Encapsulation The point of encapsulation is that it prevents other classes from knowing what your class is doing behind the scenes. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface. The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature, Encapsulation gives maintainability, flexibility and extensibility to our code. 7.3. Inheritance 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). The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself. A subclass inherits all the members (fields, methods, and nested classes) from its superclass unless restricted by private modifier (final modifier also restricts changes from sub classes). Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. Also access modifiers are used to restrict access from sub classes (e.g. private). Object-oriented Programming 37 Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class in Java is implicitly a subclass of Object. public class ToyotaCar { public String getBrand() { return "Toyota"; } } public class Corolla extends ToyotaCar { private int engineCapacity = 1500; //default value is 1500 private String model = "Corolla 141"; public Corolla() { } public Corolla(int engineCap, String model) { this.engineCapacity = engineCap; this.model = model; } public void printInfo() { System.out.println("Brand : " + getBrand()); //inheritance System.out.println("Model : " + this.model); System.out.println("Engine Capacity : " + this.engineCapacity); } } 7.3.1. this and super keywords this Constructors and methods use the keyword this quite differently. A method uses this to refer to the instance of the class that is executing the method. Static methods do not use this; they do not belong to a class instance, so this would have nothing to reference. Static methods belong to the class as a whole, rather than to an instance. Constructors use this to refer to another constructor in the same class with a different parameter list public class Corolla extends ToyotaCar { private int engineCapacity; private String model; Object-oriented Programming 38 public Corolla() { this(1500, "Corolla 141"); } public Corolla(int engineCap, String model) { this.engineCapacity = engineCap; this.model = model; } } super Methods and constructors both use super to refer to a superclass, but in different ways. Methods use super to execute an overridden method in the superclass, as the following example illustrates: public class ToyotaCar { private String color; public ToyotaCar(String color) { this.color = color; } public String getColor() { return color; } } public class Corolla extends ToyotaCar { private int engineCapacity; private String model; public Corolla() { this(1500, "Corolla 141"); //this() must be the first statement } public Corolla(int engineCap, String model) { super("White"); //super() must be the first statement this.engineCapacity = engineCap; this.model = model; } public void printInfo() { Object-oriented Programming 39 System.out.println("Brand : " + super.getColor()); System.out.println("Model : " + this.model); System.out.println("Engine Capacity : " +this.engineCapacity); } } Important The following constructor is wrong! public Corolla() { super(); this(1500, "Corolla 141"); //ERROR this() and super() together } 7.4. Polymorphism Generally, polymorphism refers to the ability to appear in many forms. Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon, in other words, the ability of a reference variable to change behaviour according to what object instance it is holding. Overloading, overriding and dynamic method binding are three types of polymorphism. 7.4.1 Overload In Java, it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. The overloaded methods must differ in the type and/or the number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. It is also important to note that the constructors can also be overloaded. 7.4.2 Override Override methods are methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used. Dynamic (or late) method binding Dynamic binding is the ability of a program to resolve references to subclass methods at runtime. As an example, assume that two subclasses (Car and Bowser) have been created Object-oriented Programming 40 based on the Vehicle abstract class, each having their own pickUp() method. Although each method reference is to a Vehicle (but no vehicle objects exist), the program is will resolve the correct method reference at runtime. Overloading example Method overloading public class MotorBike { private String startMethod = "kick"; public void start(String method) { startMethod = method; System.out.println(startMethod + " starting..."); } public void start() { System.out.println(startMethod + " starting..."); //default } } Constructor overloading public class Fruit { private String code; private String name; private int unitPrice; private int numberOfItems = 0; public Fruit() { } public Fruit(String code, String name, int unitPrice) { this.code = code; this.name = name; this.unitPrice = unitPrice; } } Overriding example public class Vitz2003 { public void start() { System.out.println("Insert the key and rotate"); } public void stop() { Object-oriented Programming 41 //… } } public class Vitz2009 extends Vitz2003 { //redefine the start method public void start() { System.out.println("Keep the key with you and" + " push start button"); } } Dynamic Binding example (using Abstract Classes) public abstract class Vehicle { private short speed = 0; private byte gear = 0; public abstract String description(); public abstract void pickUp(); public void setGear(byte gear) { this.gear = gear; } } public class Car extends Vehicle { public String description() { return "I am a Car "; } public void pickUp() { setGear((byte)1); } public void engineStop() { setGear((byte)1); } } public class Bowser extends Vehicle { @Override public String description() { return "I am a Bowser "; } Object-oriented Programming 42 @Override public void pickUp() { super.setGear((byte)2); //notice the super keyword } } public class App { public static void main(String[] args) { Vehicle c = new Car(); //Car c = new Car(); is also okay Vehicle b = new Bowser(); //Bowser c = new Bowser(); is also okay c.pickUp(); b.pickUp(); } } Method overloading rules example: import java.io.IOException; import java.sql.SQLException; public class Super { public void facultyGames(String a) throws IOException { System.out.println("23 Games"); } public void m1(){ System.out.println("Doing basic configuration"); } protected void m3(){ } public final void m4() { } //cannot override (final) public void m5() throws SQLException { } public int m6() { return 0; } } Object-oriented Programming 43 import java.io.IOException; public class Sub extends Super { public void facultyGames(String a) throws IOException { System.out.println("25 Games"); } public void m1() { super.m1(); //calls super m1 method System.out.println("Apply more configuration"); } private void m3() { //error! cannot reduce the visibility, protected -> //private } public void m5() throws IOException { //error!, cannot throw more checked exceptions } public void m6() { //error!, m6 must return int type } } 7.5. Abstract classes and Interfaces Abstract Classes 1. An abstract class is a class that contains zero or more (often one or more) abstract methods An abstract class cannot be instantiated, but abstract classes can have constructors 2. Another class (Concrete class) has to provide an implementation of abstract methods – Concrete class has to implement all abstract methods of the abstract class to be used for instantiation – Concrete class uses extends keyword Interfaces 1. It defines a standard and public way of specifying the behaviour of classes - Defines a contract (or abilities) 2. All methods of an interface are public and abstract methods before JDK 8. Later JDK introduced default keyword for method implementation in interfaces. Also, now (after JDK 8) interfaces can have static methods. - Defines the signatures of a set of methods, without the body (implementation of the methods) 3. A concrete class must implement all abstract methods defined in interfaces. Object-oriented Programming 44 4. It allows classes, regardless of their locations in the class hierarchy, to implement common behaviours and abilities. It also helps to bring multiple inheritance behaviour to the solution. Example 01: Polimarphism and Inheritance public interface Car { void changeGear(); //default access is public void applyBrake(); } public abstract class AbstractCar implements Car { //abstract class may implement Interfaces public abstract void horning(); public void changeGear() { } public void applyBrake() { } } public class Crown extends AbstractCar implements Hybrid { public void idleOff() { } public void horning() { } } public class Celsior extends AbstractCar implements Hybrid, Luxury { public void accessGps() { } public void idleOff() { } public void horning() { } } public class MarkX extends AbstractCar implements Luxury { public void accessGps() { } public void horning() { } } import java.util.ArrayList; import java.util.List; public class CarPark{ //next chapter Generics! Object-oriented Programming 45 private List park = new ArrayList(); public void add(T t) { park.add(t); } } public class App { public static void main(String[] args) { CarPark kandyCityCenter = new CarPark(); CarPark