Inheritance. Polymorphism, Interface, Abstract
Inheritance. Polymorphism, Interface, Abstract
Oriented
1
Programming
Inheritance, Polymorphism, Interface and Abstract Class
2 Inheritance: Definition
in Java, you specify another class as your parent by using the keyword
extends
public class CheckingAccount
extends BankAccount {
class BankAccount {
private double myBal;
public BankAccount() { myBal = 0; }
public double getBalance() { return myBal; }
}
System.out.println(b);
System.out.println(f);
Output:
Ed $9.0
Jen $9.0 (Fee: $2.0)
15 UML class diagrams
an industry-standard way
to draw pictures of your
classes and their
relationships to each
other
classes are boxes that list
the fields, methods, and
constructors of the type
classes that have
inheritance relationships,
or are tightly related to
each other, are
connected by arrows
16 Class Diagram: Single Class
attributes (fields) are written as
accessModifier name : type
where accessModifier is one of
- for private
+ for public
# for protected
example: - mySize: int
syntax:
super(args); // call parent’s constructor
super.fieldName // access parent’s field
super.methodName(args); // or method
24 super example
if the superclass has a constructor that requires any arguments (not ()), you must put a
constructor in the subclass and have it call the super-constructor (call to super-constructor must be
the first statement)
BankAccount b = new
FeeAccount("Ed", 9.00);
b.withdraw(5.00);
System.out.println(b.getBalance());
((BankAccount)o).withdraw(5.00);
34 Down-casting and runtime
((String)o).toUpperCase(); //
crashes
((FeeAccount)o).withdraw(5.00); //
crashes
35 A dynamic binding problem
class A {
public void method1() { System.out.println(“A1”); }
public void method3() { System.out.println(“A3”); }
}
class B extends A {
public void method2() { System.out.println(“B2”); }
public void method3() { System.out.println(“B3”); }
}
var1.method1();
var1.method2();
var2.method1(); OUTPUT???
((A)var2).method3();
36 A problem with interfaces