Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.

Similar presentations


Presentation on theme: "Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and."— Presentation transcript:

1 Inheritance

2 Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and – you add new methods and fields to adapt your new class to new situations. Inheritance is a mechanism through which a class can be defined in terms of an existing class. It supports the concept of hierarchical classification Employee class :- manager is an employee – “is- a” r/ship is the hallmark of inheritance.

3 Superclass & subclass

4 An Example

5 In terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass Superclass & subclass

6 An Example To define a subclass from a superclass – use extends keyword in Java. E.g class Manager extends Employee { Added methods and fields }

7 Types of inheritance Single Inheritance Multiple Inheritance Multilevel Inheritance Hybrid Inheritance

8 Inheritance – So far A fundamental mechanisms for code reuse in OOP- inheritance. It allows new classes to be derived from an existing class. The new class (subclass, subtype, derived class, child class) can inherit members from the old class (superclass, supertype, base class, parent class). The subclass can add new behavior and properties, and under certain circumstances, modify its inherited behavior.

9 Inheritance The keyword extends indicates that you are making a new class that derives from an existing class. Subclasses have more functionalities than their superclasses. Add new methods to subclasses. class Manager extends Employee { private double bonus; //added feature to Manager class public void setBonus(double b) { bonus = b; }

10 Member access Inheritance of members is closely tied to their declared accessibility. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed. but they exist in the subclass object. the subclass can use the inherited members as if they were declared in its own class body.

11 Accessibility of data members A subclass in includes all of the members of its superclass, it cant access those members of the superclass that have been declared as private. All inheritance in Java is public inheritance. All the public members and protected members are inherited as public and protected respectively.

12 A Scenario class A { int a; int getA() { return a; } void setA(int v) { a=v; } class B extends A { int b; int getB() { return b; } void setB(int v) { b=v; }

13 A Scenario A objA=new A(); B objB= new B(); a getA() setA(int v) a b getA() setA(int v) getB() setB(int v)

14 Inheritance in Java A class in Java can only extend one other class; that is, it can only have one immediate superclass.

15 Method overriding When designing classes, you place the most general methods into the superclass, and more specialized methods in the subclass. The getSalary method should return the sum of the base salary and the bonus.

16 Method overriding You need to supply a new method to override the superclass method A subclass can add fields, and it can add or override methods of the superclass. However, inheritance can never take away any fields or methods

17 The getSalary method of the Manager class has no direct access to the private fields of the superclass public double getSalary() { return salary + bonus; // won't work } We need to indicate that we want to call the getSalary method of the Employee superclass, not the current class. You use the special keyword super for this purpose: The call super.getSalary() calls the getSalary method of the Employee class. Method overriding

18 Here is the correct version of the getSalary method for the Manager class: public double getSalary() { double baseSalary = super.getSalary(); return baseSalary + bonus; } Method overriding

19 The super keyword super is a special keyword that directs the compiler to invoke the superclass method.

20 Constructor call Constructors are called in order of derivation, from superclass to subclass

21 Super super has two general forms:- – the first calls the superclass’ constructor – the second is used to access a member of the superclass that has been hidden by a member of a subclass. The instruction super(n, s, year, month, day); is shorthand for “call the constructor of the Employee superclass with n, s, year, month, and day as parameters.”

22 super Since the Manager constructor cannot access the private fields of the Employee class, it must initialize them through a constructor. The constructor is invoked with the special super syntax. The call using super must be the first statement in the constructor for the subclass. the super keyword has two meanings: – to invoke a superclass method, and – to invoke a superclass constructor.

23 Preventing Inheritance Final Classes & Methods Classes that cannot be extended are called final classes, and you use the final modifier in the definition of the class to indicate this. You can also make a specific method in a class final. If you do this, then no subclass can override that method.

24 final keyword Using final with inheritance – final has three uses:- it can be used to create the equivalent of a named constant Using final to prevent overriding Using final to prevent inheritance

25 Abstract classes A superclass that declares the structure of a given abstraction without providing a complete implementation of every method. A superclass that only defines a generalized form that will be shared by all its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. Shape– area() ; Triangle – its own implementation of area(), square, circle…

26 Abstract classes To require that certain methods be overridden by the subclasses – use abstract type modifier Subclass’ responsibility – as no implementation in superclass. Any class that contains one or more abstract method must also be declared as abstract. You cannot declare abstract constructors or abstract static method. Although abstract classes cannot be used to instantiate objects, they can be used to create object references

27 Abstract Classes Abstract classes can have concrete data and methods. Abstract classes cannot be instantiated. That is, if a class is declared as abstract, no objects of that class can be created. Note that you can still create object variables of an abstract class, but such a variable must refer to an object of a non-abstract subclass and subclass of the latter.

28 Runtime Polymorphism – Dynamic method dispatch Method overriding forms the basis :- Dynamic method dispatch. It’s a mechanism by which a call to an overridden method is resolved at run-time, rather than compile time.

29 Runtime Polymorphism – Dynamic method dispatch Its important because this is how Java implements run-time polymorphism. When an overridden method is called through a superclass reference, Java determines which version of that method to execute based on the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time Dynamic method lookup is the process of determining which method definition a method signature denotes during runtime, based on the type of the object.

30 Object: The Cosmic Superclass The Object class is the ultimate ancestor—every class in Java extends Object. The ultimate superclass Object is taken for granted if no superclass is explicitly mentioned. Because every class in Java extends Object, it is important to be familiar with the services provided by the Object class. In Java, only the primitive types (numbers, characters and boolean values) are not objects. All array types are class types that extend the Object class.

31 The equals and toString methods The equals method in the Object class tests whether or not one object is equal to another. If you want to test objects for equality, you will need to override equals for a more meaningful comparison. Similarly need to override toString() method. Another important method in Object is the toString method that returns a string that represents the value of this object. Almost any class will override this method to give you a printed representation of the object's current state.

32 finalize() protected void finalize() Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

33 Why no multiple inheritance in Java? instanceof keyword. Explore the Object class

34 Interfaces Using the keyword interface, you can fully abstract a class' interface from its implementation. Using interface you specify what a class must do, but not how it does. Syntactically similar to classes, but lack instance variables and methods are abstract and public. To implement an interface, a class must create the complete set of methods defined by the interface

35 Defining an interface interface name {..... }

36 Defining an interface default or public access specifier. public - it shud be the only public i/f - same file name Each class that includes an interface must implement all of the methods Variables can be declared inside interface declarations - but implicitly are final and static - they cannot be changed by the implementing class - they must also be initialized. All methods are implicity public.

37 Implementing an interface. One or more classes can implement an interface. class C implements i/fname,... { } The methods that implement an interface must be declared public. To make a class implement an interface, two steps:- – You declare that your class intends to implement the given interface – You supply the definitions for all the methods in the interface. Interfaces can be extended - using the extends keyword

38 More on interfaces Interface are not classes. You can never use new operator to instantiate an interface - cant construct interface objects, you can still declare interface variables. An interface variable must refer to an object of a class that implements the interface. Why interfaces why not abstract classes?

39 Packages

40 A package in Java is an encapsulation mechanism that can be used to group related classes, interfaces, and subpackages. A package hierarchy represents an organization of the Java classes and interfaces. It does not represent the source code organization of the classes and interfaces.

41 Packages Each Java source file (also called compilation unit) can contain zero or more definitions of classes and interfaces, but the compiler produces a separate class file containing the Java byte code for each of them. A class or interface can indicate that its Java byte code be placed in a particular package, using a package declaration. The package statement has the following syntax: package ; A class can use all classes from its own package and all public classes from other packages.

42 Two schemes First, all the classes and interfaces in a source file will be placed in the same package. Secondly, several source files can be used to specify the contents of a package.

43 Defining a package Simply include a package command as the first statement in a Java source file. The package statement defines a namespace in which classes are stored. If not mentioned – class names are put to default package. E.g:- package MyPackage (creates a package called MyPackage) Java uses file system directories to store packages. The package statement simply specifies to which package the classes defined belong to. A package hierarchy must reflect to the file system of Java development system.

44 CLASSPATH Packages are mirrored by directories How does Java run-time system know where to look for packages that you create? First the JRE – uses the current working directory. Then in the paths set in the CLASSPATH environment variable Or in the –classpath option in the javac tool.

45 CLASSPATH CLASSPATH Variables:- – Java compiler and interpreter searches the.class files in the path specified in the CLASSPATH variable. – The current working directory is by default included in this variable.

46 Access Protection


Download ppt "Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and."

Similar presentations


Ads by Google