0% found this document useful (0 votes)
36 views

Inheritance in Java: CS 3331 Fall 2009

Inheritance in Java allows classes to extend other classes to model "is-a" relationships. Subclasses inherit all public and protected members of the parent class. Constructors in subclasses can invoke parent constructors using super() and can call other constructors in the same class using this(). Fields are initialized before constructors, and parent constructors are called before child constructors. Overriding allows subclasses to provide their own implementation of a method in the parent class, while hiding refers to fields or methods with the same name as a parent but which are not overridden.

Uploaded by

iamajorge10
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Inheritance in Java: CS 3331 Fall 2009

Inheritance in Java allows classes to extend other classes to model "is-a" relationships. Subclasses inherit all public and protected members of the parent class. Constructors in subclasses can invoke parent constructors using super() and can call other constructors in the same class using this(). Fields are initialized before constructors, and parent constructors are called before child constructors. Overriding allows subclasses to provide their own implementation of a method in the parent class, while hiding refers to fields or methods with the same name as a parent but which are not overridden.

Uploaded by

iamajorge10
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 32

Inheritance in Java

CS 3331 Fall 2009

Outline

Overloading Inheritance and object initialization Subtyping Overriding Hiding

Overloading of Methods and Constructors

Def. Overloading
The ability to allow different methods or constructors of a class to share the same name.
public class Point { public Point() { /* */ } public Point(int x, int y) { /* */ } public double distance(Point other) { /* */ } public double distance(int x, int y) { /* */ } public double distance() { /* */ } // } method overloading
constructor overloading

Overloading (Cont.)

Which overloaded method to invoke?


Resolved at compile-time with signature matching, where signature is name and parameter types.
Constructors/Methods
1: Point() 2: Point(int x,int y) 3: double distance(Point other) 4: double distance(int x,int y) 5: double distance()

Signatures
Point() Point(int,int) distance(Point) distance(int,int) distance()

Point p1 = new Point(); // which constructor? Point p2 = new Point(10,20); p2.distance(p1); // which method? p2.distance(20,30); p2.distance();
4

When to Overload?
When there is a general, nondiscriminative description of the functionality that fits all the overloaded methods.
public class StringBuffer { public StringBuffer append(String str) { /* */ } public StringBuffer append(boolean b) { /* */ } public StringBuffer append(char c) { /* */ } public StringBuffer append(int i) { /* */ } public StringBuffer append(long l) { /* */ } // }

When to Overload? (Cont.)


When all the overloaded methods offer the same functionality, with some of them providing default arguments.
public class String { public String substring(int i, int j) { // base method: return substring from index i to j - 1. } public String substring(int i) { // provide default argument return substring(i, length()); } // }

Outline

Overloading Inheritance and object initialization Subtyping Overriding Hiding

Inheritance

Inheritance models the is-a relationship. If class S extends class T, then all objects of S can act-like an object of T. Only single inheritance is allowed among classes. All public and protected members of a superclass are accessible in the subclasses.*

*All protected members are also accessible within the package.

Constructors of Subclasses

Can invoke a constructor of the direct superclass.

super() must be the first statement. If the super constructor call is missing, by default the no-arg super() is invoked implicitly.

Can also invoke another constructor of the same class.

this() must be the first statement.

Example of this Calls


public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public Point() { // default constructor this.x = 0; this(0,0); this.y = 0; } }

10

Example of super Calls


public class ColoredPoint extends Point { private Color color;
public ColoredPoint(int x, int y, Color color) { this.x = x; super(x,y); this.y = y; this.color = color; } Point

-x: int -y: int


+Point() +Point(x: int, y: int)

public ColoredPoint(int x, int y) { this(x, y, Color.BLACK); // point with default value } public ColoredPoint() { color = Color.BLACK; }

// what will be the values of x and y?

}
11

Default Constructor

If no constructor is defined, the following form of no-arg default constructor is automatically generated by the compiler.
public ClassName() { super(); } Q. What would be the use of default constructor?

12

Execution Order of Constructors


Rule: Superclass first and field initialization first - Instance variable initializer vs. instance initializer (or initialization block)
Example: S x = new S(); public class S extends T { int y = 30; // 3: third public class T { int x = 10; // 1: first public T() { x = 20; // 2: second } // ... }

public S() { super(); y = 40; // 4: fourth } // ...


}

13

Exercise

What value will be printed and why?


class Super { protected int x = 100; } class Sub extends Super { { x = 200; }

public static void main(String[] args) { System.out.println(new Sub().x); }


}

14

Exercise

What are the room number and capacity of the following two objects, respectively?
ClassRoom c1 = new ClassRom(100); ClassRoom c2 = new ClassRoom(300, 100); class ClassRoom extends Room { private int capacity = 60; public ClassRoom(int c) { capacity = c; } public ClassRoom(int n, int c) { super(n); } { if (number % 2 == 1) capacity *= 2; } } class Room { private int number = 100; public Room() { this(++nextNum); } public Room(int n) { number = n; } private static int nextNum = 100; static { nextNum += 100; } { number += 2; } }
15

Outline

Overloading Inheritance Subtyping Overriding Hiding

16

Types

Whatre types?

Sets of values To statically detect program errors, called type errors. Typed- vs. untyped-languages (also, static vs. dynamic typing) Primitive types (e.g., boolean, int, long, etc.) Classes (e.g., Object, String, etc.) Interfaces (e.g., Runnable, List, etc.) Array types (e.g., int[], Object[], List[][], etc.)

Why types?

Types in Java

17

Subtyping

Whats subtyping?

Subset relationship among types (e.g., Manager is a subtype (or subset) of Employee) Subtypes values are legitimate values of supertypes. Can organizes types into hierarchy, called subype hierarchy Can extend programs by adding subtypes Between classes (subclassing) Between interfaces (subinterfacing) Between classes and interfaces (implementation or realization) Between arrays

Why subtyping?

Subtyping in Java

18

Substitution Property

Def. Substitution property

A value of subtype can appear where a value of its supertype is expected, e.g., in arguments, results, receivers, and assignments.

// 1. argument // public void register(Student s); register(new PhDStudent(Joe)); // 2. return value public Student find(String name) { // I am lazy, so I am going to return Joe every time. return new PhDStudent(Joe); } // 3. receiver of method call // toString in the class Object new PhDStudent(Joe).toString();
19

Substitution Property (Cont.)

Rules of (polymorphic) assignment

The type of expression at the right-hand side of an assignment must be a subtype of the type of the variable at the left-hand side of the assignment.

class Student { } class Undergraduate extends Student { } class Graduate extends Student { } Student s1, s2; s1 = new Undergradute(); // polymorphic assignment s2 = new Graudate(); // polymorphic assignment Graduate s3 = s2; // is this OK? Graduate s3 = (Graduate) s2; // explicit casting
20

Widening and Narrowing

Def. widening and narrowing

The conversion of a subtype to one of its supertype is called widening, and the conversion of a supertype to one of its subtype is called narrowing (or downcasting).

// s is a stack of strings Stack s = new Stack(); s.push(Hello); // widening: void push(Object) // Stack defines a method top, i.e., public Object top(). s.top().size(); // okay? ((String) s.top()).size(); // downcasting

21

Outline

Overloading Inheritance Subtyping Overriding Hiding

22

Overriding Methods

Def. Overriding

Refers to the introduction of an instance method in a subclass that has the same name, signature, and return type of a method declared in the superclass.
Implementation of the method in the subclass replaces the implementation of the method in the superclass

Consequences

23

Overriding Methods (Cont.)


public class T { public void m() { } } public class S extends T { public void m() { } } T t = new T(); S s = new S(); t.m(); // invoke m of class T s.m(); // invoke m of class S

24

Overriding Methods (Cont.)

Dynamic dispatch (binding): The method to be invoked is determined at runtime by the runtime type of the object, not by the declared type (static type).
class Student { public int minCredits() { return 12; } } class GraduateStudent extends Student { public int minCredits() { return 9; } } Student s; // s.minCredits(); // which minCredits method?
25

Overriding Methods (Cont.)

Q. How overriding differ from overloading?

26

Implementation of Dynamic Binding

Storage structure of instance variables

Class instance records (CIRs) store the state of an object The CIR for a subclass adds its new fields to the parent CIR.
Virtual Method Tables (VMTs) are used for dynamic binding.

Dynamic bindings of messages to methods

27

Dynamic Binding (Cont.)


class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } } class ColoredPoint extends Point { private Color color; public ColoredPoint(int x, int y, Color c) { super(x, y); color = c; } public Color getColor() { return color; } }
CIR for Point x y

CIR for ColoredPoint x y color

28

Dynamic Binding (Cont.)


ColoredPoint p = new ColoredPoint(10,20,Color.RED); p.getColor(); p.getX(); Point.class super: vmt: p: class: x: 10 y: 20 color: ColoredPoint.class Object.class super: vmt:

getX: getY:

super: vmt:
Color.RED

getColor:

Q: What if getX is overridden in ColoredPoint?


29

Outline

Overloading Inheritance Subtyping Overriding Hiding

30

Hiding Fields and Class Methods

Def. Hiding

Refers to the introduction of a field (instance or class) or a class method in a subclass that has the same name as a field or class method declared in the superclass.
Statically resolved (bound) at compile-time vs. dynamically dispatched at run-time

Hiding vs. overriding

31

Example
class Student { protected String description = Student; public String getDescription() { return description; hiding of } field } class Undergraduate extends Student { protected String description = Undergraduate; } new Student().getDecription(); // what value is returned? new Undergraduate().getDescription(); // what value?

Q. How to refer to hidden fields?

32

You might also like