Download presentation
Presentation is loading. Please wait.
Published byJean Carson Modified over 5 years ago
2
Topics Interfaces Abstract Classes Final Classes Enumerations
3
Using Interfaces for Algorithm Reuse
Interface types are used to express common operations. An interface is a collection of method declarations. An interface has no variable declarations or method bodies. Describes a set of methods that a class can be forced to implement. It is up to the class implementing the interface to implement ALL the method bodies
4
Syntax 10.1 Declaring an Interface
public interface InterfaceName { // method signatures } Example:Measuarable.java public interface Measurable { double getMeasure(); You can have more than 1 method declaration (no implementation) Methods are public by default Saved as Measuarable.java
5
Example1 Coin class implementing Measurable interface:
BankAccount class can implement Measurable interface too! public class Coin implements Measurable { public double getMeasure() return value; } . . . public class BankAccount implements Measurable { public double getMeasure() return balance; } . . . X PERSON ^ || STUDENT PROFESSOR TA TA implements Teachable{… private int experience; } Professor implements Teachable{..} OR ==================================== Professor extends Person Implements Employee Student extends Person TA extends Student Implements Employee public class TA implements Employee { void RaiseSalary( double d ) { // actual code here } double GetSalary() { // actual code here }
6
<<Interface>> Emplyee
Example2 Person Professor Student <<Interface>> Emplyee TA public class TA extends Student implements Employee { void RaiseSalary( double d ) { // actual code here } double GetSalary() { // actual code here } } public class Professor extends Student implements Employee
7
Defining an Interface Type
You CAN create types of interface type: E.g. Measurable measurable; An interface type has no constructor. You CANNOT create objects/instances from an interface E.g. Measurable measurable = new Measurable() //WRONG! You CAN create objects from a class implementing the interface E.g. Measurable measurable = new Coin() //OK Interface has NO instance variables All interface methods are abstract
8
Example Given that Measurable interface and BankAccount class implementing Measurable interface are implemented: OK WRONG! OK OK WRONG! Cant call methods not in Interface Measure
9
Syntax 10.2 Implementing an Interface
A class can implement multiple interfaces
10
Programming Question Implement the Measurable interface (Measurable.java) Then implement the Measurable interface in BankAccount class Test BankAccount class: public static void main(String[] args) { Measurable account1 = new BankAccount(0); System.out.println("account1.getMeasure() : "+account1.getMeasure()); }
11
Answer Measurable.java /**
Describes any class whose objects can be measured. */ public interface Measurable { Computes the measure of the object. @return the measure double getMeasure(); }
12
Answer BankAccount.java
public class BankAccount implements Measurable{ private double balance; public BankAccount() { balance = 0; } public BankAccount(double initialBalance) { balance = initialBalance; } public void deposit(double amount) { balance = balance + amount; } public void withdraw(double amount) { balance = balance - amount; } public double getBalance() { return balance; } public double getMeasure() { return balance; } public static void main(String args[]) { Measurable account1 = new BankAccount(0); System.out.println("account1.getMeasure() : "+account1.getMeasure()); }
13
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
14
<<interface>> Shape
Another Example <<interface>> Shape draw() resize() implements Circle draw() resize() Line draw() resize() Rectangle draw() resize() extends Square draw() resize()
15
Example Defining static constants in interface is OK
public interface Shape { double PI = 3.14; // static and final => upper case void draw(); // automatic public void resize(); // automatic public } public class Rectangle implements Shape { public void draw() {System.out.println ("Rectangle"); } public void resize() { /* do stuff */ } public class Square extends Rectangle { public void draw() {System.out.println ("Square"); } Defining static constants in interface is OK
16
Interfaces vs Inheritance
A class can implement more than one interface: public class Country implements Measurable, Named A class can only extend (inherit from) a single superclass. An interface specifies the behavior that an implementing class should supply - no implementation. A superclass provides some implementation that a subclass inherits. Develop interfaces when you have code that processes objects of different classes in a common way. E.g. Notepad, Word, PowerPoint, Excel applications print/display
17
Question What is wrong with this code?
Measurable meas = new Measurable(); System.out.println(meas.getMeasure());
18
Answer Answer: Measurable is not a class. You cannot construct objects of type Measurable.
19
Question Assuming Country class implements Measurable interface, What is wrong with this code? Measurable meas = new Country("Uruguay", ); System.out.println(meas.getName());
20
Answer Answer: The variable meas is of type Measurable, and that type has no getName method.
21
Converting From Classes to Interfaces
You can convert from a class type to an interface type, provided the class implements the interface. BankAccount account = new BankAccount(1000); Measurable meas = account; // OK if BankAccount implements // Measurable interface OK because BankAccount class implements Measurable interface NOT OK because String class does NOT implement Measurable interface
22
Variables of Class and Interface Types
Figure 3 An Interface Reference Can Refer to an Object of Any Class that Implements the Interface Method calls on an interface reference are polymorphic The appropriate method is determined at run time. Coin? Or BankAccount?
23
Example
24
Casting from Interfaces to Classes
Method to return the object with the largest measure: public static Measurable larger( Measurable obj1, Measurable obj) { if (obj1.getMeasure() > obj2.getMeasure()) return obj1; return obj2; } Returns the object with the larger measure, as a Measurable reference. Country uruguay = new Country("Uruguay", ); Country thailand = new Country("Thailand", ); Measurable max = larger(uruguay, thailand); You need a cast to convert from an interface type to a class type. Country maxCountry = (Country) max; //cast to class OK String name = maxCountry.getName(); If you are wrong and max doesn't refer to a Country object, the program throws an exception at runtime.
25
Abstract Classes When you extend an existing class, you have the choice whether or not to override the methods of the superclass. Sometimes, it is desirable to force programmers to override a method. That happens when there is no good default for the superclass, and only the subclass programmer can know how to implement the method properly. E.G Employee { getname(){ ….} //base implementation make sense computeSalary(){return 2000;} //base implementation does not make sense b/s u have either salaried emps or commission emps in a company, not general emps //subclasses should override it –WE WANT TO FORCE PROGRAMMER TO OVERRIDE IT //but overriding is OPTIONAL– compiler will not complain even if programmer does not } SalariedEmployee extends Emplyee {…………….} CommissionEmployee extends Employee {………………}
26
Example Even if we implement this method, there is no
Employee SalariedEmployee CommissionEmployee Even if we implement this method, there is no Proper implementation. Only subclasses can provide a suitable implementation (why? There are only either Salaried employees or Commission employees in a company) So we like to FORCE subclass to override the method. Right now overriding this method is optional in subclasses
27
Solution: Abstract classes and methods
Use keyword abstract declare class abstract declare the method as an abstract method in superclass (no implementation) Now any subclasses are FORCED to implement this abstract method (OR subclass needs to be declared abstract too!)
28
Subclass implement inherited abstract method
Subclass chose not to implement inherited abstract method. So subclass MUST be declared abstract
29
Even if subclass has no own/inherited abstract methods that are not implemented, it can choose to define class abstract. This is to avoid creating objects from this class.
30
Abstract Classes An abstract method has no implementation.
This FORCE the implementers of subclasses to specify concrete implementations of this method. You cannot construct objects of a abstract class you can still have a variable whose type is an abstract class. Actual object to which it refers must be an instance of a concrete subclass A class for which you cannot create objects is called an abstract class. A class for which you can create objects is sometimes called a concrete class.
31
Example: creating object
Employee: abstract class CommissionEmployee: concrete class OK NOT OK OK
32
Abstract Classes Which classes MUST be declared abstract?
A class that declares an abstract method A class that inherits an abstract method without overriding it Optionally, if you want, declare classes with no abstract methods as abstract. Doing so prevents programmers from creating instances of that class but allows them to create their own subclasses.
33
Previous example again..
A class that declares an abstract method A class that inherits an abstract method without overriding it Optionally, if you want, declare classes with no abstract methods(not declared/not inherited) as abstract.
34
Abstract Classes Why use abstract classes?
To FORCE programmers to create subclasses. By specifying certain methods as abstract you avoid the trouble of coming up with useless default methods that others might inherit by accident. abstract classes can have: instance variables, concrete methods and constructors.
35
Programming Question Implement the abstract class Shape:
Instance variables: color [type string] Constructor: 1-arg constructor that initialize color Instance method: toString that print “ Shape of color=the color” Abstract method: getArea that return area of the shape Subclass Rectangle: Instance variables: length, width Constructor: 3-arg constructor that initaize color,length,width Instance method: override toString to print instance variable values method: overrde getArea that return area of the Rectangle
36
Answer Shape.java public abstract class Shape { private String color; public Shape (String color) { this.color = color; public String toString() { return "Shape of color=" + color; public abstract double getArea();
37
Rectangle.java public class Rectangle extends Shape { private int length; private int width; public Rectangle(String color, int length, int width) { super(color); this.length = length; this.width = width; public String toString() { return "Rectangle of length=" + length + " and width=" + width + ", subclass of " + super.toString(); public double getArea() { return length*width;
38
Triangle.java public class Triangle extends Shape { private int base; private int height; public Triangle(String color, int base, int height) { super(color); this.base = base; this.height = height; public String toString() { return "Triangle of base=" + base + " and height=" + height + ", subclass of " + super.toString(); public double getArea() { return 0.5*base*height;
39
TestShape.java public class TestShape { public static void main(String[] args) { Shape s1 = new Rectangle("red", 4, 5); System.out.println(s1); System.out.println("Area is " + s1.getArea()); Shape s2 = new Triangle("blue", 4, 5); System.out.println(s2); System.out.println("Area is " + s2.getArea()); // Cannot create instance of an abstract class //Shape s3 = new Shape("green"); // Compilation Error!! }
40
Final Methods and Classes
Occasionally, you may want to prevent other programmers from creating subclasses or from overriding certain methods. Opposite of abstract methods In these situations, you use the final reserved word E.g. String class in Java library is final: i.e. nobody can extend (create subclasses of) the String class
41
You can also declare individual methods as final:
Class need not be final
42
Common Error Overriding Methods to Be Less Accessible
If a superclass declares a method to be publicly accessible, you cannot override it to be more private in a subclass. E.g. superclass: BankAccount E.g subclass: CheckingAccount The compiler does not allow this
43
Enumeration Types A special data type that enables for a variable to be a set of predefined constants The variable must be equal to one of the predefined values.
45
An enumeration type variable can be null. E.g.
the status variable in the previous example can actually have three values: SINGLE, MARRIED, and null.
46
Programming Question Download TaxReturn.java and TaxCalculator.java from class website and study the code. The TaxReturn.java uses two int constants to denote SINGLE and MARRIED status: public static final int SINGLE = 1; public static final int MARRIED = 2; Declare a new class FilingStatus.java with following enumeration to represent above 2 constants: public enum FilingStatus{SINGLE, MARRIED} Modify the TaxReturn class to do the following: Declare getTax() method final Modify class to use FilingStatus for status instead of above 2 constants.
47
Answer FilingStatus.java public enum FilingStatus{SINGLE, MARRIED}
48
TaxReturn.java CONTINUED.. 1 import java.util.Scanner; 2 /**
3 A tax return of a taxpayer in 2008. 4 */ 5 public class TaxReturn 6 { 7 private static final double RATE1 = 0.10; 8 private static final double RATE2 = 0.25; 9 private static final double RATE1_SINGLE_LIMIT = 32000; 10 private static final double RATE1_MARRIED_LIMIT = 64000; 11 12 private double income; 13 private FilingStatus status; 14 15 /** Constructs a TaxReturn object for a given income and marital status. @param anIncome the taxpayer income @param aStatus either SINGLE or MARRIED 20 */ 21 public TaxReturn(double anIncome, FilingStatus aStatus) 22 { income = anIncome; status = aStatus; 25 } 26 CONTINUED..
49
27 public final double getTax()
28 { double tax1 = 0; double tax2 = 0; 31 if (status == FilingStatus.SINGLE) { if (income <= RATE1_SINGLE_LIMIT) { tax1 = RATE1 * income; } else { tax1 = RATE1 * RATE1_SINGLE_LIMIT; tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT); } } else { if (income <= RATE1_MARRIED_LIMIT) { tax1 = RATE1 * income; } else { tax1 = RATE1 * RATE1_MARRIED_LIMIT; tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT); } } 56 return tax1 + tax2; 58 }
50
59 60 public static void main(String[] args) 61 { Scanner in = new Scanner(System.in); 63 System.out.print("Please enter your income: "); double income = in.nextDouble(); 66 System.out.print("Are you married? (Y/N) "); String input = in.next(); FilingStatus status; if (input.equals("Y")) { status = FilingStatus.MARRIED; } else { status = FilingStatus.SINGLE; } 78 TaxReturn aTaxReturn = new TaxReturn(income, status); 80 System.out.println("Tax: “ + aTaxReturn.getTax()); 83 } 84}
51
Inner Classes An inner class X is a class whose declaration is nested within the declaration of another class Y. The syntax of an inner class declaration is as follows: public class OuterClassX //outer class { // Declare outer class features, as desired ... details omitted. // We declare an INNER class wholly within the BODY of the OUTER class. // Note: inner classes are NOT declared to be public - they are only // "visible" as a type to the outer class in which they are declared. class InnerClassY //inner class // Declare the inner class's features ... // details omitted. }
52
Inner Classes The purpose of declaring an inner class:
conceal the fact that the class exists from the application Invents a private type that only the enclosing outer class knows about. Enclosing outer class can declare variables of type inner class Anywhere else, we cannot! Attempting to do so will produce a “cannot find symbol” compiler error E.g. Let’s look at a specific example of an inner class called GradeBook, declared within the Course class.
53
Inner class Example: import java.util.*;
public class Course //OUTER CLASS { private String name; private ArrayList<Student> enrolledStudents; private GradeBook gradeBook; public Course(String name) { this.name = name; enrolledStudents = new ArrayList<Student>(); gradeBook = new GradeBook(); } public void assignGrade(Student s, String grade) { gradeBook.setGrade(s, grade); public String lookUpGrade(Student s) { return gradeBook.getGrade(s); class GradeBook { //INNER CLASS private HashMap<Student, String> grades; public GradeBook() { grades = new HashMap<Student, String>(); public void setGrade(Student s, String grade) { grades.put(s, grade); public String getGrade(Student s) { return grades.get(s); } // end inner class declaration } // end outer class declaration Inner class
54
Inner Classes Assume Student.java is as follows:
public class Student{ String name; public Student(String name) { this.name = name; } public String getName() { return this.name; } } We may write client code as follows: Here’s the output: public class MyApp { public static void main(String[] args) { Course c = new Course("MATH 101"); Student s1 = new Student("Fred"); c.assignGrade(s1, "B-"); Student s2 = new Student("Cynthia"); c.assignGrade(s2, "A+"); System.out.println(s1.getName() +" received a grade of " + c.lookUpGrade(s1)); System.out.println(s2.getName() +" received a grade of " + c.lookUpGrade(s2)); }
55
Inner Classes However, if we were to try to reference GradeBook as a type anywhere outside of the Course class: We get the following compiler error public class MyApp { public static void main(String[] args) { // This won't compile! GradeBook is not known as a type outside of the // Course class boundaries. GradeBook gb = new GradeBook(); // etc.
56
Inner Classes What happens in compilation?
When a class containing an inner class definition is compiled, we wind up with separate bytecode files named OuterClass.class and OuterClass$InnerClass.class, respectively E.g. Course.class and Course$GradeBook.class
57
Programming Question Implement the Company (outer) class with following: Inner class: Employee Instance variable: name 1-arg constructor that initialize employee name Instance method getName that return employee name Inner class: Department 1-arg constructor that initialize department name Instance method getName that return department name Instance method : newStarter: Accepts employee name and department name as parameters Create an employee object and department object Print “employe XXX is a member of department “”YY” main method: Company c = new Company(); c.newStarter("Henry", "IT");
58
Answer Company.java public class Company { class Employee {
private String name; Employee(String name) { this.name = name; } public String getName() {return name; } } class Department { Department (String name) { this.name = name; } public String getName() { return name; } public void newStarter(String name, String department) { Employee emp = new Employee(name); Department dpt = new Department(department); System.out.println(emp.getName() + " is a member of " + dpt.getName()); public static void main(String[] args) { Company c = new Company(); c.newStarter("Henry", "IT");
59
Relationships Between Objects
Inheritance Implementation (interfaces) Association Dependency Aggregation composition Association Implements/ Realizes Inheritance Dependency Aggregation Composition UML Notation
60
Association A relationships between two different classes
E.g. Professor advises Student One-to-many : one professor advises may students. A student is advised by only one Professor 1 *
61
* *
62
* Implementation: 1 Class Professor { …
ArrayList<Student> advisees; } Class Student { … Professor advisor; }
63
Aggregation A special form of association
Alternatively referred to as the consists of, is composed of, or has a relationship
64
For example, a car is composed of an engine, a transmission, four wheels
so if Car, Engine, Transmission, and Wheel were all classes, then we could form the following aggregations: A Car contains an Engine. A Car contains a Transmission. A Car is composed of many (in this case, four) Wheels. UML Syntax:
65
E.g. University is composed of schools
Notice that we can get by without using aggregation: Association and aggregation are rendered in code in precisely the same way
66
* Implementation: 1 Class Whole { … Arraylist<PartA> parAList;
PartB partB; } * Class PartA Whole whole; Class PartB 1
67
Composition Composition is a strong form of aggregation
The “parts” cannot exist without the “whole.” E.g., relationship = “a Book is composed of many Chapters” we could argue that a chapter cannot exist if the book to which it belongs ceases to exist; E.g. relationship = “a Car is composed of many Wheels”, A wheel can be removed from a car and still serve a useful purpose. Book–Chapter relationship as composition and the Car–Wheel relationship as aggregation.
68
UML Diagram: Book is composed of Chapters
69
Implementation * Class Book { … ArrayList<Chapter> chapters; }
Class Chapter Book book; *
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.