Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance-Basics.

Similar presentations


Presentation on theme: "Inheritance-Basics."— Presentation transcript:

1 Inheritance-Basics

2 INHERITANCE BASICS Reusability is achieved by INHERITANCE
Java classes Can be Reused by extending a class. Extending an existing class is nothing but reusing properties of the existing classes. The class whose properties are extended is known as super or base or parent class. The class which extends the properties of super class is known as sub or derived or child class A class can either extends another class or can implement an interface

3 Various Forms of Inheritance
Single Inheritance Hierarchical Inheritance A A X X B B A B C A B C NOT SUPPORTED BY JAVA MultiLevel Inheritance Multiple Inheritance SUPPORTED BY JAVA A A A B A B B B C C C C

4 Forms of Inheritance WRONG WRONG
Multiple Inheritance can be implemented by implementing multiple interfaces not by extending multiple classes Example : class Z extends A implements C , D { …………} OK class Z extends A ,B class Z extends A extends B { { OR } } A C D Z WRONG WRONG

5 Defining a Subclass Syntax : class <subclass name> extends <superclass name> { variable declarations; method declarations; } Extends keyword signifies that properties of the super class are extended to sub class Sub class will not inherit private members of super class

6 single inheritance or one level inheritance
class A {   int x;   int y;   int get(int p, int q){     x=p; y=q; return(0);     }     void Show(){       System.out.println(x);       } } class B extends A{   public static void main(String args[]){     A a = new A();     a.get(5,6);     a.Show();     }     void display(){       System.out.println("B");       } }

7 Multilevel Inheritance
class A {   int x;   int y;   int get(int p, int q){     x=p; y=q; return(0);     }     void Show(){       System.out.println(x);       } } class B extends A{   void Showb(){     System.out.println("B");     } }

8 class C extends B{ void display(){ System. out
class C extends B{   void display(){     System.out.println("C");   }   public static void main(String args[]){     A a = new A();     a.get(5,6);     a.Show();     } }

9 Protected access specifier
public class A{ protected void msg(){System.out.println("Hello");} } class B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); }

10 Access Control public protected default private Yes No
Access Modifiers Access Location public protected default private Same Class Yes sub classes in same package No Other Classes in Same package Subclasses in other packages Non-subclasses in other packages

11 Usage of super key word

12 Usage of super key word-cont...
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.

13 Usage of super key word-cont...
Asubclass can call a constructor defined by its superclass by use of the following form of super: super(arg-list); Here, arg-list specifies any arguments needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass’ constructor.

14 Usage of super key word-cont...
Let’s review the key concepts behind super( ). When a subclass calls super( ), it is calling the constructor of its immediate superclass. Thus, super( ) always refers to the superclass immediately above the calling class. This is true even in a multileveled hierarchy. Also, super( ) must always be the first statement executed inside a subclass constructor.

15 A Second Use for super The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member Here, member can be either a method or an instance variable

16 Usage of super key word-cont...
This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass.

17 Usage of super key word-cont...
// Using super to overcome name hiding. class A { int i; }

18 Usage of super key word-cont...
class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B }

19 Usage of super key word-cont...
void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); }

20 Usage of super key word-cont...
class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); }

21 Usage of super key word-cont...
This program displays the following: i in superclass: 1 i in subclass: 2

22 Method Overriding

23 Method Overriding In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass.

24 Method Overriding-cont...
Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. DEMO

25 Dynamic Method Dispatch

26 Dynamic Method Dispatch-cont...
Method overriding forms the basis for one of Java’s most powerful concepts: dynamic method dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism.

27 Dynamic Method Dispatch-cont...
// Dynamic Method Dispatch class A { void callme() { System.out.println("Inside A's callme method"); }

28 Dynamic Method Dispatch-cont...
class B extends A { // override callme() void callme() { System.out.println("Inside B's callme method"); }

29 Dynamic Method Dispatch-cont...
class C extends A { // override callme() void callme() { System.out.println("Inside C's callme method"); }

30 Dynamic Method Dispatch-cont...
class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A

31 Dynamic Method Dispatch-cont...
r = a; // r refers to an A object r.callme(); // calls A's version of callme r = b; // r refers to a B object r.callme(); // calls B's version of callme r = c; // r refers to a C object r.callme(); // calls C's version of callme }

32 Dynamic Method Dispatch-cont...
The output from the program is shown here: Inside A’s callme method Inside B’s callme method Inside C’s callme method

33 Using final with Inheritance
The keyword final has three uses. First, it can be used to create the equivalent of a named constant. The other two uses of final apply to inheritance. Using final to Prevent Overriding. Using final to Prevent inheritance.

34 Packages: Putting Classes Together

35 Packages Packages are Java’s way of grouping a number of related classes and/or interfaces together into a single unit. That means, packages act as “containers” for classes. The benefits of organising classes into packages are: The classes contained in the packages of other programs/applications can be reused. In packages classes can be unique compared with classes in other packages. That two classes in two different packages can have the same name. If there is a naming clash, then classes can be accessed with their fully qualified name. Classes in packages can be hidden if we don’t want other packages to access them. Packages also provide a way for separating “design” from coding.

36 Java Foundation Packages
Java provides a large number of classes groped into different packages based on their functionality. The six foundation Java packages are: java.lang Contains classes for primitive types, strings, math functions, threads, and exception java.util Contains classes such as vectors, hash tables, date etc. java.io Stream classes for I/O java.awt Classes for implementing GUI – windows, buttons, menus etc. java.net Classes for networking java.applet Classes for creating and implementing applets

37 Using System Packages The packages are organised in a hierarchical structure. For example, a package named “java” contains the package “awt”, which in turn contains various classes required for implementing GUI (graphical user interface). java “java” Package containing “lang”, “awt”,.. packages; Can also contain classes. lang awt Graphics awt Package containing classes Font Classes containing methods Image

38 Accessing Classes from Packages
There are two ways of accessing the classes stored in packages: Using fully qualified class name java.lang.Math.sqrt(x); Import package and use class name directly. import java.lang.Math Math.sqrt(x); Selected or all classes in packages can be imported: Implicit in all programs: import java.lang.*; package statement(s) must appear first import package.class; import package.*;

39 Using a Package DEMO

40 Visibility Modifiers

41 Abstract Class

42 Abstract Classes When we define a class to be “final”, it cannot be extended. In certain situation, we want to properties of classes to be always extended and used. Such classes are called Abstract Classes. An Abstract class is a conceptual class. An Abstract class cannot be instantiated – objects cannot be created. Abstract classes provides a common root for a group of classes, nicely tied together in a package:

43 Abstract Class Syntax abstract class ClassName {
... abstract Type MethodName1(); Type Method2() // method body } When a class contains one or more abstract methods, it should be declared as abstract class. The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods.

44 Abstract Class -Example
Shape is a abstract class. Shape Circle Rectangle

45 The Shape Abstract Class
public abstract class Shape { public abstract double area(); public void move() { // non-abstract method // implementation } Is the following statement valid? Shape s = new Shape(); No. It is illegal because the Shape class is an abstract class, which cannot be instantiated to create its objects.

46 Abstract Classes public Circle extends Shape { protected double r;
protected static final double PI = ; public Circle() { r = 1.0; ) public double area() { return PI * r * r; } } public Rectangle extends Shape { protected double w, h; public Rectangle() { w = 0.0; h=0.0; } public double area() { return w * h; }

47 Abstract Classes Properties
A class with one or more abstract methods is automatically abstract and it cannot be instantiated. A class declared abstract, even with no abstract methods can not be instantiated. A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them. A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated.

48 Interfaces Design Abstraction and a way for loosing realizing Multiple Inheritance

49 Interfaces Interface is a conceptual entity similar to a Abstract class. Can contain only constants (final variables) and abstract method (no implementation) - Different from Abstract classes. Use when a number of classes share a common interface. Each class should implement the interface.

50 Interface - Example <<Interface>> Speaker speak()
Politician Priest Lecturer speak() speak() speak()

51 Interfaces Definition
Syntax (appears like abstract class): Example: interface InterfaceName { // Constant/Final Variable Declaration // Methods Declaration – only method body } interface Speaker { public void speak( ); }

52 Implementing Interfaces
Interfaces are used like super-classes who properties are inherited by classes. This is achieved by creating a class that implements the given interface as follows: class ClassName implements InterfaceName [, InterfaceName2, …] { // Body of Class }

53 Implementing Interfaces Example
class Politician implements Speaker { public void speak(){ System.out.println(“Talk politics”); } class Priest implements Speaker { public void speak(){ System.out.println(“Religious Talks”); } class Lecturer implements Speaker { public void speak(){ System.out.println(“Talks Object Oriented Design and Programming!”); }

54 Extending Interfaces Like classes, interfaces can also be extended. The new sub-interface will inherit all the members of the superinterface in the manner similar to classes. This is achieved by using the keyword extends as follows: interface InterfaceName2 extends InterfaceName1 { // Body of InterfaceName2 }

55 Inheritance and Interface Implementation
A general form of interface implementation: This shows a class can extended another class while implementing one or more interfaces. It appears like a multiple inheritance (if we consider interfaces as special kind of classes with certain restrictions or special features). class ClassName extends SuperClass implements InterfaceName [, InterfaceName2, …] { // Body of Class }

56 Interfaces and Software Engineering
Interfaces, like abstract classes and methods, provide templates of behaviour that other classes are expected to implement. Separates out a design hierarchy from implementation hierarchy. This allows software designers to enforce/pass common/standard syntax for programmers implementing different classes. Pass method descriptions, not implementation Java allows for inheritance from only a single superclass. Interfaces allow for class mixing. Classes implement interfaces.

57 Abstract Class Vs Interfaces
Difference between an interface and an abstract class? Abstract Class Vs Interfaces Abstract class Interface Abstract class is a class which contain one or more abstract methods, which has to be implemented by its sub classes. Interface is a Java Object containing method declaration but no implementation. The classes which implement the Interfaces must provide the method definition for all the methods. Abstract class is a Class prefix with an abstract keyword followed by Class definition. Interface is a pure abstract class which starts with interface keyword. Abstract class can also contain concrete methods. Whereas, Interface contains all abstract methods and final variable declarations. Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented.

58 Hackerrank Exercises


Download ppt "Inheritance-Basics."

Similar presentations


Ads by Google