Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Java 2 Programming

Similar presentations


Presentation on theme: "Introduction to Java 2 Programming"— Presentation transcript:

1 Introduction to Java 2 Programming
Lecture 5 Inheritance

2 Overview Inheritance …and Encapsulation …and Constructors …and Methods
Including overriding and overloading Controlling Inheritance

3 Quick Recap Inheritance defines parent-child relationships
Base (or super) class, and derived (or sub-) class Child inherits all functionality of its parent Typically add new methods and member variables One of the basic features of all OO languages Already encountered it in Robocode All your robots extend a provided Robot base class All robocode events extend an Event base class You can extend almost any object With a couple of extensions as we’ll see…

4 Using Inheritance Use the extends keyword in the class definition:
public class MyRobot extends Robot { } A class can only extend one base class Unlike C++ Java doesn’t allow multiple inheritance All Java classes extend a common base class (java.lang.Object) Automatically assumed by the compiler, unless you say otherwise Provides some basic functionality, e.g. toString() and equals() public class Calculator extends Object {

5 Inheritance and Encapsulation
Sub-classes inherit all their superclass member variables But may not be able to access them directly! The visibility modifiers, public, protected, and private apply Only public and protected are accessible Private member variables of a base class cannot be altered by a sub-class (except via a method) Tip: Try to avoid breaking encapsulation by making variables private, unless you’re expecting the class to “have children”

6 Inheritance and Encapsulation
public class Person { private String _name; private String _ ; //can be access by sub-classes protected int _salary; public String getName() {…} public String setName() {…} }

7 Constructors Revisited
Constructors can call one another Allows initialisation code to be kept in one place (not duplicated between constructors) Use the this keyword to call another constructor in the same class Must be first line in the constructor public class Bookmark { public Bookmark(String url) { this( new URL(url) ); } public Bookmark(URL url) { //other initialisation code

8 Inheritance and Constructors
An class must ensure that its parent is properly initialised, by calling one of its constructors Use the super keyword Even if a constructor isn’t explicitly called a call to the default constructor is added by compiler Base class constructors are called first Inheritance happens from the top down …ancestors, parent, child…

9 Constructors public class Parent { private String msg;
public Parent() {} public Parent(String message) { msg = message; } public class Child extends Parent {   public Child()  {    super("Parent message");  public class OtherChild extends Parent {

10 Method Overloading A Java class can define several methods with the same name, so long as the parameters are different, the return type is the same public int doSomething(String s, String s2); public int doSomething(String s); public int doSomething(int x, int y); Java determines the correct method to call by checking the parameters Useful to provide variants of a method that work on different types of object Typically one method does all the work, and the others call it As with constructors, this collects common code into a single method

11 Method Overriding A sub-class can define a method with the same name and parameters as as base class Known as overriding Useful when some aspect of the base class behaviour must be altered To completely change the implementation, just define a new version (in the child) To partially change the implementation use the super keyword to refer to the parents original implementation

12 Inheritance and Methods
What happens when we call a method? The JVM tries to find the implementation of that method and then execute the code Starts searching with the objects class, then works upward to its parent…its parent’s parent…etc, etc. Searching for methods works from the bottom-up Reverse of how constructors are called Also explains how a sub-class can substitute its own behaviour for a base class JVM finds that first.

13 Worked Example In an E-Commerce system we might have a class responsible for calculating prices e.g:  public class Pricer { public float calculatePrice(Product p) //implementation details irrelevant for example } The Product parameter lets the Pricer calculate the price

14 Worked Example Assume we want to extend this functionality so that the calculation also includes tax (i.e. adding on VAT). US purchases don't include tax, but UK ones do, so we can't just rewrite the original method. Instead we create a subclass, called UKPricer that does the extra work.  public class UKPricer extends Pricer { public float calculatePrice(Product p) //this implementation will also add on VAT… }

15 Worked Example Ideally we want to reuse the code in the base class, as all we need to do is add on the extra 17.5% to the final price. We can do better than copy-and-paste using super… public class UKPricer extends Pricer { public float calculatePrice(Product p)   //call the superclass method   float withoutTax = super.calculatePrice(p);   float tax = withoutTax * 17.5 / 100;  return withoutTax + tax; }

16 Controlling Inheritance – Restricting
Inheritance can be restricted using the final keyword Applies to both methods and classes A final class cannot be extended A final method cannot be overridden public final class MyClass { } public class OtherClass { public final int aMethod() { … }

17 Controlling Inheritance – Enforcing
Inheritance can be forced by using the abstract keyword Again applies to both methods and classes An abstract class must be extended, cannot be used to create objects An abstract method must be overrided by a sub-class A class with at least one abstract method must be declared abstract public abstract class SomeOtherClass { public int aMethod() { … } public abstract void otherMethod(); }


Download ppt "Introduction to Java 2 Programming"

Similar presentations


Ads by Google