CSC 240 Inheritance
CSC 240 Inheritance
Zhen Jiang
Dept. of Computer Science
West Chester University
West Chester, PA 19383
[email protected]
10/30/2019 1
Table of Contents
Introduction to inheritance
Inheritance
Syntax
More!
Overridding
OOP (object-oriented programming)
Polymorphism
Modifiers
Abstract class and interfaces
GUI
10/30/2019 2
Introduction
Write an Employee class with methods that
return values for the following properties of
employees at a particular company:
10/30/2019 3
// A class to represent employees
public class Employee {
public int getHours() {
return 40; // works 40 hours / week
}
10/30/2019 7
Inheritance: Is-a relationship
is-a relationship: A hierarchical connection where
one category can be treated as a specialized version
of another.
Examples:
Every secretary is an employee.
Every square is a rectangle.
Every dog is a mammal.
10/30/2019 8
code reuse: The practice of writing program code once and using
it in many contexts.
10/30/2019 10
Syntax
Creating a subclass, general syntax, p625:
public class <subclass name> extends <superclass name>
Example:
public class Secretary extends Employee
{
....
}
10/30/2019 12
Writing even more classes
Write a Marketer class that represents marketers
who have the same properties as general employees,
but instead of making only a paltry $40,000,
marketers make $50,000!
10/30/2019 13
Overriding methods
override: To write a new version of a method in a
subclass to replace the superclass's version.
10/30/2019 14
Marketer class
// A class to represent marketers
public class Marketer extends Employee {
public void advertise() {
System.out.println("Act now while supplies last!");
}
10/30/2019 15
OOP: Based in reality or too
convenient?
At many companies, all new employees attend a
common orientation to learn general rules (e.g., what
forms to fill out when).
10/30/2019 17
Why not just have a 22-page manual for lawyers,
21-page manual for secretaries, 23-page manual for
marketers, etc…?
10/30/2019 18
maintenance: If a common rule changes, only the
common manual needs to be updated.
10/30/2019 19
The 20 page manual manner is useful to be able to
specify general rules that will apply to many groups.
Locality
A person can look at the manual for lawyers and
quickly discover all rules that are specific to lawyers.
10/30/2019 22
Constructor for superclass
10/30/2019 23
public class Employee {
private double salary;
public Employee(double initialSalary)
{
salary = initialSalary;
}
public int getHours() {
return 40; // 40 hours per week
}
public double getSalary() {
return salary;
}
public int getVacationDays() {
return 10; // 2 weeks' paid vacation
}
public String getVacationForm() {
return "yellow"; // use the yellow form
}
}
10/30/2019 24
Use the super() method to call the superclass’s constructor, p634
public class Marketer extends Employee {
// inherits double salary
10/30/2019 25
Question: If a method is declared private, does a
subclass inherit it?
Actually, yes. Subclasses inherit everything that they
don’t override.
If a method is declared private, can a subclass
call it?
NO! Only code inside the same class can call a private
method.
What if you want a subclass to be able to use it?
Use the protected access level
10/30/2019 26
public class Employee {
private double salary = 40000.00;
addToSalary(1000000.00);
}
}
10/30/2019 32
//base class //sub class
public class ProA { public class ProB extends ProA {
private int x = 1; public int getB(){
protected void setX(int a){ setX(2);
x=a; // your next step is to return x
} // but “return x” does not work
// due to the private modifier, so
protected int getX(){ return getX();
return x; }
} }
}
10/30/2019 34
Employee Laura = new Lawyer();
System.out.println(Laura.getSalary()); // 40000.0
System.out.println(Laura.getVacationForm()); // "pink"
10/30/2019 35
public class Secretary extends Employee public class Marketer extends Employee {
{ public void advertise() {
public void takeDictation(String text) { System.out.println("Act now while supplies last!");
System.out.println("Taking dictation of text: " }
+ text);
} public double getSalary() {
} return 50000.0; // $50,000.00 / year
}
}
10/30/2019 37
Exercises
Assume that the following four classes have been declared:
public class Foo { public class Baz extends Foo {
public void method1() { public void method1() {
System.out.println("foo 1"); System.out.println("baz 1");
} }
10/30/2019 38
What would be the output of the following client
code?
10/30/2019 39
10/30/2019 40
The code produces the following output:
baz
baz 1
foo 2
foo
foo 1
bar 2
baz
baz 1
mumble 2
foo
foo 1
foo 2
10/30/2019 41
Kind of override under the standard of
superclass!
10/30/2019 42
Variable Shadowing:
Something to avoid!!
Polymorphism applies to methods in Java
But not to fields! A a1 = new A();
A a2 = new B();
public class A { System.out.println(a1.method()); // prints 1
int x = 1; System.out.println(a2.method()); // prints 2
10/30/2019 43
Variable Shadowing:
When a class extends another class and
defines a field with the same name, each
object of the subclass contains two fields
with that name.
The supclass’s version of the field is said
10/30/2019 46
Exercises
Slide 39
PolymorphismDemo in
http://www.cs.wcupa.edu/~zjiang/Poly.zip
10/30/2019 47
How to determine overriding and
shadow?
Method, overriding, own study processing
Attribute, shadow, >60 is a passing score
so that you cannot override it
10/30/2019 48
Modifiers
Public
A class, method, constructor, interface etc declared public
can be accessed from any other class. Therefore fields,
methods, blocks declared inside a public class can be
accessed from any class belonging to the Java Universe.
Because of class inheritance, all public methods and
variables of a class are inherited by its subclasses.
10/30/2019 49
Private
Methods, Variables and Constructors that are declared
private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level.
Class and interfaces cannot be private.
Variables that are declared private can be accessed outside
the class only if public accessor methods are present in the
class.
10/30/2019 50
Protected
Variables, methods and constructors which are declared
protected in a superclass can be accessed only by the
subclasses.
Protected access gives the subclass a chance to use the
helper method or variable, while preventing a nonrelated
class from trying to use it.
10/30/2019 51
Default (like public)
Default access modifier means we do not explicitly declare
an access modifier for a class, field, method etc.
A variable or method declared without any access control
modifier is available to any other class in the same package.
For example:
public class Logger {
String format;
String getFormat() { return this.format; }
public void setFormat(String f) { format = f; }
}
10/30/2019 52
Abstract and Interfaces
What have you learnt from the above exercises
on “extends”?
Is it good to block the use of subclass method that is
not declared in super class?
Good, because methods can be in template. In the
54
final Example
// A class to represent employees
public class Employee {
public int getHours() {
return 40; // works 40 hours / week
}
Or to methods:
// subclasses cannot override the getSalary method
public final double getSalary() { return salary; }
Or even to classes:
// the Employee class cannot be extended
// It can’t have any subclasses at all!
public final class Employee { ... }
56
Opposite of final
The final keyword prevents subclasses from
changing (overriding) code
66
Interfaces
Let's say you have the following two
related classes:
public class Scientist { public class Engineer {
public void discover() { public void discover() {
System.out.println(“Eureka! I System.out.println(“Cool, what did
have found it!“); I just do?“);
} }
public void publish() { public void publish() {
System.out.println(“My System.out.println(“I don't
research is better than yours.”); know how this happened, but it
} works.”);
}
}
}
interface Researcher {
void discover();
void publish();
}
68
Using Interface Objects
public static void researchCycle(Researcher r) {
r.discover();
r.publish();
}
researchCycle(researcher1);
researchCycle(researcher2);
}
69
Using Interfaces
Interfaces are a way of specifying what objects are
capable of, without saying how.
71
public class Engineer implements Researcher {
public void discover() {
System.out.println(“Whoa, what did I just do?“);
}
72
Exercise
Create an interface Measurable class
with an non-abstract getArea() method
Write subclasses Rectangle and Circle to
implement the above interface
Write main methods for each that
construct an object and print its area.
Do not use attribute to store area
information.
public interface Measurable{ public class shapeApp {
public abstract double getArea(); } public static void main(String [] args){
Rectangle r = new Rectangle(2, 3);
public class Circle implements Measurable{ Circle c = new Circle(1.5);
private double radius; System.out.println(r.getArea());
public Circle (double r){ System.out.println(c.getArea());
radius = r; } }
}
public double getArea (){
return Math.PI*radius*radius; } 6.0
7.0685834705770345
public double getCircumference(){
return radius; }
}
10/30/2019 77
Explanation of
interfacehttp://docs.oracle.com/javase/tutoria
l/java/concepts/interface.html
Exercises
Revisit ButtonDemo.java in
http://www.cs.wcupa.edu/~zjiang/button.zip
10/30/2019 79
GUI
Window interface, p755
JFrame
Basic components
Button
see the button sample available in Chapter 0 from class website
Event
Multiple events (e.g., which button is clicked?)
Label
Text field
Layouts, p787
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Other Buttons
https://docs.oracle.com/javase/tutorial/uiswing/components/button.html
Color
Complete package of the samples of the above
https://www.cs.wcupa.edu/~zjiang/csc142_java_sample.htm