1 / 36

Inheritance

Inheritance. Chapter 5. Chapter 5. 5.0 Inheritance Inheritance concept Access levels Inheriting instances fields and methods Object class and method overriding Array of sub classes Three-level inheritance. Inheritance: Terminology.

Télécharger la présentation

Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Inheritance Chapter 5

  2. Chapter 5 • 5.0 Inheritance • Inheritance concept • Access levels • Inheriting instances fields and methods • Object class and method overriding • Array of sub classes • Three-level inheritance

  3. Inheritance: Terminology There are a number of terms that you need to know in understanding inheritance. • Field : a variable that is part of a class • Method : a function that is part of a class • Constructor : a special method that is called when an object is created • Superclass : the class that is inherited from (parent class) • Subclass : the class that does the inheriting (child class) • extends: in Java the keyword extendsmeans that a class will inherit from another class • Overload : a method is overloaded if there are two or more methods with the same name in a class. Each overloaded method has a different set of parameters. That's how you can tell which one will get called. • Override : a method is overridden if there is a method in the subclass that has the same name and the same set of parameters. The superclass method is then NOT inherited.

  4. Inheritance: Concept • Object-oriented programming allows classes to inherit commonly used state and behaviour from other classes. • The idea of inheritance is simple but powerful. When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. • Inheritance is a mechanism for a subclass to reuse code from a superclass. • You can reuse fields and methods of the existing class without having to write them yourself. • A mechanism that enables one class to inherit, both the behaviour and the attributes of another class. • Inheritance allows a software developer to derive a new class from an existing one.

  5. Inheritance: Concept • 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. • A subclass inherits all the members (fields, methods and nested classes) from its superclass. • Constructors are not members, so they are not inherited by subclasses but the constructors of the superclass can be invoked from the subclass.

  6. Inheritance: Concept • Superclass typically is-a general purpose class. • Subclass is a special case or customized version of the superclass. • When subclass is created, it inherits data and methods from its superclass. • Format for class inheritance is: class mySuperClass { //data and methods for the superclass} • Subclass is usually located in its own java file. class mySubClass extends mySuperClass { ….. }

  7. Inheritance: Concept • Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class. Inheritance should create an is-a relationship, meaning the child is more specific version of the parent Employee ContractEmployee

  8. Inheritance: Benefit of Inheritance Question: What are the benefits of inheritance? • State and functionality can be "shared" among objects: Inheritance reduces program development time by allowing us to reuse code. When we extend a class someone else has already built, we only need to add our changes. This is especially useful in the context of modifying code. Since all the shared code is inherited, any changes in the top level classwill be automatically propagated to all subclasses. • Substitutability/Polymorphism: A subclass can be used wherever an object of the superclassis required. An object of a single class can have multiple forms: either its own or that of one of the classes it extends. • Specialization through extension: We may easily extended a class to behave like a specialized version of the superclass.

  9. Inheritance: Benefit of Inheritance Question: What are the benefits of inheritance? • code reuse • reduce software complexity • reduces program development time

  10. Inheritance: Drawback of Inheritance Question: What are the drawbacks of inheritance? • Forces inheritance of specification, and does not check for true subtype relationship. • Subclasses are highly dependent on implementation of the superclass. Thus, "design and document for inheritance, or else prohibit it". • Inheritance forces a set of methods and fields on a class. You may not want some of these, and it is not necessary that all of these are required. There is no concept of partial inheritance.

  11. Inheritance: Access Level: Variables and Methods public • Accessible anywhere class name is accessible protected • Accessible in the package that contains the class • Accessible in all subclasses private • Accessible in the class only If no access level is given: • Accessible in the package that contains the class. • Accessible in subclasses defined in the package that contains the class. • Not accessible in subclasses defined outside the package that contains the class.

  12. Inheritance: Access Level: Variables and Methods Method Visibility Modifier Can be Accessed By public any class protected owning class, any subclass, any class in the same package Private owning class No Modifier owning class, any class in the same package

  13. Inheritance: Implementation • A class diagram is a visual tool that provides you with an overview of a class. • It consists of a rectangle divided into three sections, the top section contains name of the class, middle section contains name and data types of the attributes and the bottom section contains the methods. The Employee class diagram

  14. Superclass: class Employee Inheritance: Implementation public class Employee{ //class private int empNum; //attributes private double empSal; public Employee(){ //constructor empNum=0; empSal=0.0; } public Employee(int n, double s){ //constructor empNum=n; empSal=s; } public int setEmpNum(int num){ //mutator return empNum= num; } public double setEmpSal(double sal){ //mutator return empSal= sal; } public int getEmpNum(){ //acessor return empNum; } public double getEmpSal(){ //acessor return empSal; } }

  15. Inheritance: Implementation • You can create another class called EmployeeTerritoryand provide three fields (empNum, empSal, empTerritory). Where empNum, empSal will be inherited from Employee The figure shows the relation between Employee and the EmployeeTerritory is inheritance relationship.

  16. Inheritance: Implementation • When using inheritance to create EmployeeTerritory, programmer • Save time because Employee fields and methods already exist • Reduce errors because the Employee methods have already been used and tested • Reduce the amount of learning required to use the new class • A class may be the parent for a child class and may be a child of another class. Just as with human relationships, a person is a child of some humans and a parent to others. • The syntax for deriving a child class from a parent class is: class childClass extends parentClass { // new characteristics of the child class go here}

  17. Inheritance: Implementation: extends • In Java, we use the reserved word extendsto establish an inheritance relationship. • To instantiates the object, such as: EmployeeTerritory AseanRep= new EmployeeTerritory(); AseanRep.getEmpNum(); AseanRep.getEmpSal(); AseanRep.getEmpTerritory();

  18. Subclass: class class EmployeeTerritory extends Employee{ private int empTerritory; public EmployeeTerritory(){ super(); empTerritory=0; } public EmployeeTerritory(int n, doubles, int num){ super(n,s); empTerritory=0; } public int getEmpTerritory(){ return empTerritory; } public int setEmpTerritory(int num){ return empTerritory=num; } } establish an inheritance with Employee One instance variable Others inherited from Employee

  19. Inheritance: Implementation: Proposition • Inheritance is one-way proposition; a child inherits from a parent, not the other way around. For example Employee aClerk= new Employee(); • Employee is the parent class and aClerkis an object of the parent class. • Superclass does not have access to the subclass methods. e.g: aClerk.getEmpTerritory(); is NOT VALID • The Employee object does not have the access to EmployeeTerritory methods. • When creating the parent class, programmer does not know how many future subclasses it might have, or what their data or methods might look like.

  20. Inheritance: Implementation: Constructor • When writing a program, programmer tends to forget about initialize a library component. Thus, the resources used by the element are still retained and easily end up running out of resources (memory). • This is the reason why constructor is needed. • With constructor, a special method automatically called when an object is created. That will release the memory resources when it’s no longer being used (in additional to garbage collector). • When we start a program we always initialize a field, e.g. for(x=0; y.length() < x; x++) • Constructor works the same but instead of field it initialize the object. • With constructor, the class designer can guarantee initialization of every object.

  21. Inheritance: Implementation: Constructor What is a Constructor? • A special type of method that is called when an object is created. In Java, constructors have the same name as their class and have no return value in their declaration. • Purpose • to create an instance of a class. • Some of the differences between constructors and other Java methods: • Constructors never have an explicit return type. • Constructors cannot be directly invoked (the keyword new must be used). • Constructors cannot be overridden, nor they are inherited. • Constructors cannot be final. • Constructors cannot be abstract. • Constructors cannot be static.

  22. Inheritance: The super Reference • Accessing Superclass methods • All classes have at least one constructor. A constructor is used to initialize a new object of that type and looks like a method with the same name as the class but without a return type. • The Java constructor name is the same as the class name and is allowed multiple signatures. • When creating a class that doesn’t have constructor, Java will automatically supply a default constructor –one that never requires arguments. • When a superclass has a default constructor, you can create a subclass with or without its own constructor. However, if superclass contains only one constructor that require arguments, you must include at least one constructor for each for each subclass you create.

  23. Inheritance: The super Reference • Accessing Superclass methods • Unlike members of a superclass, constructors of a superclass are not inherited by its subclasses, even though they have public visibility. • You must define a constructor for a class or use the default constructor added by the compiler. • The following statement calls the superclass’s constructor; super(); • A constructor for a child class always starts with an invocation of one of the constuctors in the parent class. If the parent class has several constructors then the one which is invoked is determined by matching argument lists.

  24. Inheritance: Constructor & super Reference

  25. Superclass constructor Subclass constructor call superclass constructor

  26. Application class instantiates the object ?

  27. Inheritance: The this Keyword • You can use the keyword this as the opposite of super. It refers to another constructor in the same class. If used, it must be the first line of the constructor. It refer to the current object.

  28. Inheritance: The this Keyword class Parent { String name = "Parent"; } class Child extends Parent { String name = "Child"; public void print() { System.out.println( name ); System.out.println( this.name); System.out.println( super.name); System.out.println( Parent.name); System.out.println( ((Parent)this).name); } } class SuperThis{ public static void main( String args[] ) { Child whoAmI= new Child(); whoAmI.print(); } } ?

  29. Inheritance: Method Override (replace) • A method is overridden if there is a method in the subclass that has the same name and the same set of parameters. The superclass method is then NOT inherited. • Overriding means creating a new set of method statements for the same method signature (name, number of parameters and parameter types). • Method overriding is seen when a superclass and a subclass have the same named method with the identical method inputs. It is said that the method in the subclass overrides method in the superclass.

  30. Inheritance: Method Overload • Method overloading simply means that a class has several methods with the same name but different input parameters.

  31. Inheritance: Example Rectangle Box

  32. Superclass: Rectangle Inheritance: Example

  33. Inheritance: Example Rectangle Box

  34. Subclass: Box

  35. Inheritance: Example Output ? We need an application class. Rectangle Box

  36. Application class ?

More Related