Presentation is loading. Please wait.

Presentation is loading. Please wait.

Class Hierarchies. Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An.

Similar presentations

Presentation on theme: "Class Hierarchies. Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An."— Presentation transcript:

1 Class Hierarchies

2 Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An example of where this could be useful is with an employee records system. You could create a generic employee class with states and actions that are common to all employees. Then more specific classes could be defined for salaried, commissioned and hourly employees. The generic class is known as the parent (or superclass or base class) and the specific classes as children (or subclasses or derived classes). The concept of inheritance greatly enhances the ability to reuse code as well as making design a much simpler and cleaner process.

3 Inheritance in Java Java uses the extends keyword to set the relationship between a child class and a parent class For example Consider the following

4 Example class Animal1 { private String type; public Animal1(String aType) { type = aType; } public String toString() { return "This is a " + type; } } class Dog extends Animal1 { private String breed; public Dog(String name){ super(name); } }

5 Consider We have a less detailed (abstract) class Animal1 And a more detailed subclass(ie.more concrete) Dog Dog extends (that is provides more detail) the superclass Animal1

6 Another Example

7 Class B class B { int x; void setIt (int n) { x=n;} void increase () { x=x+1;} void triple () { x=x*3;}; int returnIt () { return x;} }

8 Class C class C extends B { void triple () {x=x+3;} // override existing method void quadruple () {x=x*4;} // new method }

9 Using these Classes public class GetRich { public static void main(String[] args) { B b = new B(); b.setIt(2); b.increase(); b.triple(); System.out.println( b.returnIt() ); // prints 9 C c = new C(); c.setIt(2); c.increase(); c.triple(); System.out.println( c.returnIt() ); // prints 6 }

10 Note about the class definition When a class C extends class B, C automatically has all variables and methods defined in class B. (think of it as a internal copying mechanism) If class C defines a variable or method that has the same name in class B, class C's definition overrides B's.

11 Notes In the above code, class C inherits all class B's variables and methods. Class C overrides the “triple” method, and added a “quadruple” method. Other classes can extend Class C, as to inherit all members and methods of class C (which includes those in B). In this way, a tree hierarchy is formed. When class C extends B, we say that C is a “subclass” of A, and A is the “superclass” of C. This is called inheritance, because C inherited from B. Two or more classes can inherit from the same parent class. However, a class can only have one parent. In other words, in Java, you cannot subclass from multiple classes.

12 Overloading, Overriding, and Shadowing Overloading, overriding, and shadowing are similar concepts that can be easy to confuse. Although all three techniques allow you to create members with the same name, there are some important differences. Overloaded members are used to provide different versions of a property or method that have the same name, but that accept different number of parameters, or parameters with different data types. Overridden properties and methods are used to replace an inherited property or method that is not appropriate in a derived class. Overridden members must accept the same data type and number of arguments. Derived classes inherit overridden members.

13 Shadowing Shadowed members are used to locally replace a member that has broader scope. Any type can shadow any other type. For example, you can declare a property that shadows an inherited method with the same name. Shadowed members cannot be inherited.

14 Shadowing The main purpose of shadowing is to protect the definition of your class members. The base class might undergo a change that creates an element with the same name as one you have already defined. If this happens, the Shadows modifier forces references through your class to be resolved to the member you defined, instead of to the new base class element.

15 Abstract Classes In class hierarchies, the superclass is more general than its subclass(es). The superclass contains elements and properties common to all of the subclasses. The previous example was of a concrete superclass that instance objects can be created from. Often, the superclass will be set up as an abstract class which does not allow objects of its prototype to be created. In this case, only objects of the subclass are used. To do this the reserved word abstract is included in the class definition.

16 Example public abstract class Animal // class is abstract { private String name; public Animal(String nm) // constructor method { name=nm; } public String getName() // regular method { return (name); } public abstract void speak(); // abstract method - note no {} }

17 Abstract methods These are methods with no body specification. Subclasses must provide the method statements for their particular meaning. If the method was one provided by the superclass, it would require overriding in each subclass. And if one forgot to override, the applied method statements may be inappropriate

18 Polymorphism Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. This is the third basic principle of object oriented programming. Overloading and overriding are two types of polymorphism. Now we will look at the third type: dynamic method binding. Consider the following example

19 Example public class AnimalReference { public static void main(String args[]) Animal ref // set up var for an Animal Cow aCow = new Cow("Bossy"); // makes specific objects Dog aDog = new Dog("Rover"); Snake aSnake = new Snake("Earnie"); // now reference each as an Animal ref = aCow; ref.speak(); ref = aDog; ref.speak(); ref = aSnake; ref.speak(); }

20 Example Assume that three subclasses (Cow, Dog and Snake) have been created based on the Animal abstract class, each having their own speak() method. Notice that although each method reference was to an Animal (but no animal objects exist), the program is able to resolve the correct method related to the subclass object at runtime. This is known as dynamic (or late) method binding.

21 Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc

22 Exercises 1: Create a Student Class 1 b extend the student class to create a computer student class with a login and password. Include methods to ask the user to input login and password and see if they match. 2 Create a Book class 2b Create Paperback and hardback subclasses which 3: Design a Person Class Create an employee subclass which in turn has two subclasses, workers and managers Design an appropriate Semantic net which describes the relationships, properties and methods of each class

23 abstract class Employee { String name; public abstract float calcIncome(); } class Manager extends Employee { public void hire(String who) { System.out.println( who + " hired by " + name ); } public void fire(String who) { System.out.println( who + " fired by " + name ); } }

24 Main program public class ManagerCheck { public static void main(String args[]) { Manager me = new Manager(); me.hire("newbie");"nobody"); }

25 Class Modifiers A class declaration may include class modifiers. ClassModifiers: ClassModifier ClassModifiers ClassModifier ClassModifier: one of public protected private abstract static final strictfp

26 Field Modifiers FieldModifiers: FieldModifier FieldModifiers FieldModifier FieldModifier: one of public protected private static final transient volatile

27 strictfp Classes The effect of the strictfp modifier is to make all float or double expressions within the class declaration be explicitly FP-strict This implies that all methods declared in the class, and all nested types declared in the class, are implicitly strictfp.

28 public Public access Most liberal kind of access Class or field is accessible everywhere

29 Private Private if its only visible from inside the class definition This is compromised somewhat by public access methods

30 protected If you create a protected data field or method it can be used within its own class or any subclass extended from it but not from the outside world

31 static If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized

32 final Fields A field can be declared final Both class and instance variables (static and non-static fields) may be declared final. Effectively final declares the variable to be constant

33 Transient and volatile We will go back to these


Download ppt "Class Hierarchies. Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An."

Similar presentations

Ads by Google