Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance...

35
Inheritance in Java

description

Summary Situation public protected default private Accessible to class from same package? yes no Accessible to class from different package? yes no, unless it is a subclass no

Transcript of Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance...

Page 1: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Inheritance in Java

Page 2: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Access Specifiers• private keywordprivate keyword

– Used for most instance variablesUsed for most instance variables– private variables and methods are accessible only to methods of the private variables and methods are accessible only to methods of the

class in which they are declaredclass in which they are declared– Declaring instance variables private is known as data hidingDeclaring instance variables private is known as data hiding

• public keywordpublic keyword– Exposes variables or methods outside the Class.Exposes variables or methods outside the Class.– Declaring public methods is know as defining the class’ public Declaring public methods is know as defining the class’ public

interface.interface.• Protected keywordProtected keyword

– Provides limited accessProvides limited access– Provides access to sub classes but not to the classes outside a Provides access to sub classes but not to the classes outside a

packagepackage

Page 3: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Summary Situation   public   protected   default

   private 

Accessible to class from same package?

yes yes yes no

Accessible to class from different package?

yes  no, unless it is a

subclass 

no no

 

Page 4: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Inheritance• Inheritance allows a software developer to reuse

classes by deriving a new class from an existing one• The existing class is called the parent class, or

superclass, or base class• The derived class is called the child class or

subclass.• As the name implies, the child inherits

characteristics of the parent• That is, the child class inherits the methods and

data defined for the parent class

Page 5: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Inheritance Relationship

Animal weight : int

+ getWeight() : int

Bird

Inheritance should create an Inheritance should create an is-a relationshipis-a relationship, meaning the , meaning the child child is ais a more specific version of the parent more specific version of the parent

Page 6: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Deriving Subclasses• In Java, we use the reserved word extends to establish an

inheritance relationship

class Animal{ // class contents int weight;

public void int getWeight() {…}}

class Bird extends Animal{ // class contents

public void fly() {…};}

Page 7: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Class Hierarchy

• Good class design puts all common features as high in the hierarchy as reasonable

• inheritance is transitive– An instance of class Parrot is also an instance

of Bird, an instance of Animal, …, and an instance of class Object

Page 8: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Class inheritance

• The inclusion of members of a base class in a derived class so that they are accessible in that derived class is called class inheritance.

• An inherited member of a base class is one that is accessible within the derived class.

• If a base class member is not accessible in a derived class, then it is not an inherited member of the derived class.

Page 9: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Class inheritance

• An inherited member of a derived class is a full member of that class and is freely accessible to any method in the class.

• The non- inherited members are also part of the base class object.

Page 10: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Inheriting Data Members

Page 11: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Hidden Data Members

• Variables of same name both in base class and derived class

• Use of keyword super

Page 12: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Inherited Methods

• Methods other than constructors are inherited in the same way as data members.

• The constructors are not inherited.

Page 13: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Example// A simple example of inheritance.// Create a superclass.class A {int i, j;void showij() {System.out.println("i and j: " + i + " " + j);}}// Create a subclass by extending class A.class B extends A {int k;void showk() {System.out.println("k: " + k);}void sum() {System.out.println("i+j+k: " + (i+j+k));}}

Page 14: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

class SimpleInheritance {public static void main(String args[]) {A superOb = new A();B subOb = new B();// The superclass may be used by itself.superOb.i = 10;superOb.j = 20;System.out.println("Contents of superOb: ");superOb.showij();System.out.println();

Page 15: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

/* The subclass has access to all public members of its superclass. */

subOb.i = 7;subOb.j = 8;subOb.k = 9;System.out.println("Contents of subOb: ");subOb.showij();subOb.showk();System.out.println();System.out.println("Sum of i, j and k in subOb:");subOb.sum();}}

Page 16: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

OUTPUT

• The output from this program is shown here:• Contents of superOb:• i and j: 10 20• Contents of subOb:• i and j: 7 8• k: 9• Sum of i, j and k in subOb:• i+j+k: 24

Page 17: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Example

public class Animal {public Animal(String aType) {type = new String(aType);}public String toString() {return “This is a “ + type;}private String type;}

Page 18: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

public class Dog extends Animal {// constructors for a Dog objectprivate String name; private String breed; }

Page 19: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Constructors of the Derived Classpublic class Dog extends Animal {public Dog(String aName) {super(“Dog”); name = aName; breed = “Unknown”; }public Dog(String aName, String aBreed) {super(“Dog”); name = aName; breed = aBreed; }private String name; private String breed; }

Page 20: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Overriding a Base Class Method

public String toString() {return “It’s “ + name + “ the “ + breed;}

Page 21: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Method Overriding• A child class can override the definition of an inherited method in

favor of its own– that is, a child can redefine a method that it inherits from its parent– the new method must have the same signature as the parent's method,

but can have different code in the body

• In java, all methods except of constructors override the methods of their ancestor class by replacement. E.g.:– the Animal class has method eat()– the Bird class has method eat() and Bird extends Animal– variable b is of class Bird, i.e. Bird b = …– b.eat() simply invokes the eat() method of the Bird class

• If a method is declared with the final modifier, it cannot be overridden

Page 22: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Another use of Super

public String toString() {return super.toString() + “\nIt’s “ + name + “

the “ + breed;}

Page 23: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

23

Overloading vs. Overriding

• Overloading deals with multiple methods in the same class with the same name but different signatures

• Overloading lets you define a similar operation in different ways for different data

• Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature

• Overriding lets you define a similar operation in different ways for different object types

Page 24: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Guidelines to Choose Access Attributes

• Methods likely to be used as external interface to a class should be declared as public.

• Do not make data members public unless they are constants intended for general use.

• If you expect other people will use your classes as base classes, your classes will be more secure if you keep data members private, and provide public methods for accessing and manipulating them when necessary.

Page 25: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

• Use protected when you want a limited access to the subclasses in other packages

Page 26: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

26

The Object Class

• A class called Object is defined in the java.lang package of the Java standard class library

• All classes are derived from the Object class– even if a class is not explicitly defined to be the child of

an existing class, it is assumed to be the child of the Object class

– the Object class is therefore the ultimate root of all class hierarchies

• The Object class contains a few useful methods, which are inherited by all classes– toString()– equals()– clone()

Page 27: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

The Object Class: the toString Method

• That’s why the println method can call toString for any object that is passed to it – all objects are guaranteed to have a toString method via inheritance

• The toString method in the Object class is defined to return a string that contains the name of the object’s class and a hash value

• Every time we have defined toString, we have actually been overriding it

Page 28: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

The Object Class: the equals Method

• The equals method of the Object class determines if two variables point to the same object (more shortly)

• Many classes (which all implicitly extend an Object class) override equals to define equality in some other way, e.g. Integer.equals looks at the represented integer, etc.

Page 29: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

EXAMPLE class Animal {private String type;public Animal(String aType) {type = new String(aType);}public void eat(){System.out.println("Animal eat");}}

Page 30: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

EXAMPLE class Dog extends Animal {private String name; private String breed; public Dog(String aName) {super("Dog"); name = aName; breed = "Unknown"; }public Dog(String aName, String aBreed) {super("Dog"); name = aName; breed = aBreed; }public void eat(){System.out.println("Dog eat");}}

Page 31: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

EXAMPLE class Test {public static void main(String args[]) {Animal a = new Animal(“Unknown");Animal b=a;Dog d = new Dog("dog");System.out.println(a.toString());System.out.println(b.toString());System.out.println(d.toString());System.out.println(a.equals(b));System.out.println(a.equals(d));}

Page 32: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

LAB PRACTICE

• Create a parent class “person”• Add instance variable like name.• Add methods like setname(), getname()• Create a child class “student” which inherits from person

class• Add instance variable like stunum.• Add methods like setstunum(), getstunum()• Create another class Test which contains main() method.• Create object of child class n call methods• Setname()• Setstunum()• Getname()• Getstunum()

Page 33: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

LAB PRACTICE

• Create a parent class “Bicycle”• Add instance variables like speed,gear, initialize via

constructor• Add methods like speedUp(), changeGear(),

applyBrakes(), printStates();• Create a child class “MountainBike” which inherits from

Bicycle class• Add instance variable like seatheight, initialize via

constructor.• Add methods like setHeight(), getHeight()

Page 34: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

LAB PRACTICE• Create another class Test which contains main() method.• Create object of child class n call methods• printStates()• speedUp()• changeGear()• applyBrakes()• printStates()• setHeight()• getHeight()

Page 35: Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Lab PracticeNow override printStates() method in child classCreate objects of parent class & child class in main()

Call methods for parent class in the following sequence• printStates()• speedUp()• changeGear()• applyBrakes()• printStates()Call methods for child class in the following sequence• printStates()• speedUp()• changeGear()• applyBrakes()• setHeight()• printStates()