Top Banner
INHERITANCE AUTHOR:- AHSAN RAJA
31

Inheritance Slides

Jan 12, 2017

Download

Education

Ahsan Raja
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Inheritance Slides

INHERITANCE

AUTHOR:- AHSAN RAJA

Page 2: Inheritance Slides

INHERITANCE A mechanism wherein a new class is derived from an existing class. In Java, classes may inherit or acquire the properties and methods of other classes. A class derived from another class is called a subclass, whereas the class from which a subclass is derived is calleda superclass. A subclass can have only one superclass, whereas a superclass may have one or more subclasses.class Super{ ..... ….} class Sub extends Super{ ..... …..}

Page 3: Inheritance Slides

Permits sharing and accessing properties form one to another class. To establish this relation java uses “EXTEND” keyword.

Example:class Employee{   float salary=40000;  }  class Programmer extends Employee{   int bonus=10000;   public static void main(String args[]){     Programmer p=new Programmer();     System.out.println("Programmer salary is:"+p.salary);     System.out.println("Bonus of Programmer is:"+p.bonus);  }  }  

Page 4: Inheritance Slides

ADVANTAGES OF INHERITANCE

Minimize the amount of duplicate code in an application by sharing common  code amongst several subclasses.

It also make application code more flexible to change because classes that inherit from a common  superclass can

be used interchangeably. Reusability -- facility to use public methods of base class without rewriting the

same. Data hiding -- base class can decide to keep some data private so that it cannot be

altered by the derived class. Overriding--With inheritance, we will be able to override the methods of the base

class so that meaningful  implementation of the base class method can be designed in the derived class.

Page 5: Inheritance Slides

IS-A & HAS-A Relationship

• If a class is child of another class then we have is a relation

• If an object contain an instance of a class this is called has a relation.

Page 6: Inheritance Slides

HAS-A RELATIONSHIPpackage relationships;  class Car {         private String colour;      private int maxSpeed;       public void carInfo(){          System.out.println("Car Colour= "+colour + " Max Speed= " + maxSpeed);      }      public void setColor(String colour) {          this.colour = colour;      }      public void setMaxSpeed(int maxSpeed) {          this.maxSpeed = maxSpeed;      }  }  

Page 7: Inheritance Slides

IS-A RELATIONSHIPclass Audi extends Car{   //Audi extends Car and thus inherits all methods from Car (except final and static)  public void AudiStartDemo(){   Engine AudiEngine = new Engine();   AudiEngine.start();          }   }  

Page 8: Inheritance Slides

SPECIALIZATION AND GENERALIZATIONo The process of extracting common characteristics from two or more

classes and combining them into a generalized superclass, is called Generalization. The common characteristics can be attributes or methods. Generalization is represented by a triangle followed by a line.

o Specialization is the reverse process of Generalization means creating new sub classes from an existing class.

Page 9: Inheritance Slides

There is no limit to the number of subclasses a class can have.

There is no limit to the depth of the class tree.

Subclasses are more specific and have more functionality.

Super classes capture generic functionality common across many types of objects.

Page 10: Inheritance Slides

SUB CLASS CONSTRUCTOR

a subclass constructor is used to construct the inheritance instance variable of both the subclass and super class

the subclass constructor uses the keyword super to invoke the constructor method of the super class.

Page 11: Inheritance Slides

TYPES OF INHERITANCE

A. SINGLE INHERITANCEB. MULTILEVEL INHERITANCEC. MULTIPLE INHERITANCED. HIERARCHICAL INHERITANCEE. HYBRID INHERITANCE

Page 12: Inheritance Slides

TYPE OF INHERITANCE

Single InheritanceWhen a class extends another class(Only one class) then we  call it as Single inheritance.

Page 13: Inheritance Slides

public class ClassA { public void dispA(){ System.out.println("disp() method of ClassA"); } } public class ClassB extends ClassA { public void dispB() { System.out.println("disp() method of ClassB"); } public static void main(String args[]) { ClassB b = new ClassB(); b.dispA(); b.dispB(); } }

Page 14: Inheritance Slides

Multilevel Inheritance

In Multilevel Inheritance a derived class will be inheriting a parent class and as well as the derived class act as the parent class to other class.

Page 15: Inheritance Slides

public class ClassA { public void dispA() { System.out.println("disp() method of ClassA"); } } public class ClassB extends ClassA { public void dispB() { System.out.println("disp() method of ClassB"); } } public class ClassC extends ClassB { public void dispC() { System.out.println("disp() method of ClassC"); } public static void main(String args[]) { ClassC c = new ClassC(); c.dispA(); c.dispB(); c.dispC(); } }

Page 16: Inheritance Slides

Hierarchical Inheritance

In this inheritance multiple classes inherits from a single class i.e. there is one super class and multiple sub classes.

Page 17: Inheritance Slides

public class ClassA { public void dispA() { System.out.println("disp() method of ClassA"); } } public class ClassB extends ClassA { public void dispB() { System.out.println("disp() method of ClassB"); } } public class ClassC extends ClassA { public void dispC() { System.out.println("disp() method of ClassC"); } } public class ClassD extends ClassA { public void dispD() { System.out.println("disp() method of ClassD"); } } public class HierarchicalInheritanceTest { public static void main(String args[]) { ClassB b = new ClassB();b.dispB();b.dispA();ClassC c = new ClassC();c.dispC();c.dispA(); ClassD d = new ClassD();d.dispD();d.dispA(); } }

Page 18: Inheritance Slides

Access ControlAccess control keywords define which classes can access classes, methods, and members

Modifiers Class Package Subclass WorldPublicProtectedPrivate

Page 19: Inheritance Slides

SUPER KEYWORD

It is used inside a sub-class method definition to call a method defined in the super class. Private methods of the super-class cannot be called. Only public and protected methods can be called by the super keyword.

It is also used by class constructors to invoke constructors of its parent class.

Page 20: Inheritance Slides

USE OF SUPER KEYWORD

it calls the superclass constructor

inheritance syntax :- super( parameter list);

access the member of the super class

syntax:- super. member variable;

Page 21: Inheritance Slides

class Super_class{ int num = 20;public void display(){ System.out.println("This is the display method of superclass"); } } public class Sub_class extends Super_class { int num = 10;public void display(){ System.out.println("This is the display method of subclass"); } public void my_method(){ Sub_class sub = new Sub_class();sub.display(); super.display();System.out.println("value of the variable named num in sub class:"+ sub.num); System.out.println("value of the variable named num in super class:"+ super.num); } public static void main(String args[]){ Sub_class obj = new Sub_class(); obj.my_method(); } }

Page 22: Inheritance Slides

Invoking Superclass constructorIf a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the super class. But if we want to call a parametrized constructor of the super class, you need to use the super keyword class Superclass{ int age; Superclass(int age){ this.age = age; } public void getAge(){ System.out.println("The value of the variable named age in super class is: " +age); } } public class Subclass extends Superclass { Subclass(int age){ super(age); } public static void main(String args[]){ Subclass s = new Subclass(24); s.getAge(); } }

Page 23: Inheritance Slides

Method overridingDeclaring a method in subclass which is already present in parent class is known as method overriding.

class Human{ public void eat() { System.out.println("Human is eating"); } } class Boy extends Human{ public void eat(){ // @overridingSystem.out.println("Boy is eating"); } public static void main( String args[]) { Boy obj = new Boy(); obj.eat(); }

}

Page 24: Inheritance Slides

Rules of method overriding in Java

Argument list: The argument list of overriding method must be same as that of the method in parent class. The data types of the arguments and their sequence should be maintained as it is in the overriding method.

Access Modifier: The Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class.

Private, Static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.

Must be IS-A relationship (inheritance).

Page 25: Inheritance Slides

ANOTHER EXAMPLEOF OVERRIDINGclass Animal{

public void move(){

system.out.println("animals can move"); } }

class Dog extends Animal{

public void move(){

system.out.println("dogs can walk and run"); } }

public class TestDog{

static void main(string args[])

{ Animal a = new Animal(); // animal reference and object

Animal b = new Dog(); // animal reference but dog object

a.move();// runs the method in animal class

b.move();//runs the method in dog class } }

Page 26: Inheritance Slides

PROGRAMS OF Hierachical INHERRITANCEpackage office; import java.util.Scanner; class parent { int code; String name; String address; int phonenum; void enterdata() { Scanner dc=new Scanner(System.in);//use to take string values Scanner in=new Scanner(System.in);//use to take integer value System.out.println("Enter Code="); code=in.nextInt(); System.out.println("Enter Name="); name=dc.nextLine(); System.out.println("Enter Address="); address=dc.nextLine(); System.out.println("Enter Phone-Number="); phonenum=in.nextInt(); } void display() { System.out.println("Code="+code); System.out.println("Name="+name); System.out.println("Address="+address); System.out.println("phonenum="+phonenum); } }

class Typest extends parent { int pay; void enterT() { enterdata(); Scanner in=new Scanner(System.in); System.out.println("Enterdata"); pay=in.nextInt(); } } class Officer extends parent { int pay; void enterO() { enterdata(); Scanner in=new Scanner(System.in); System.out.println("Enterdata"); pay=in.nextInt(); display(); System.out.println("Basic pay="+pay); } public class Office { public static void main(String[] args) { Typest T=new Typest(); T.enterT(); Officer O=new Officer(); O.enterO(); } }

Page 27: Inheritance Slides

Static keyword in java

The static keyword in java is used for memory management mainly. the static can be;VariableFunction/methodIt makes your program memory efficient

Static :Static keyword does not require obj it can be called without obj also the value of static keyword remains same.

Final :Final keyword stops overriding of any method or variable …

Page 28: Inheritance Slides

Class Student8{Int rollno; String name;Static String college=“ITS”;Student8(int r, String n){rollno=r;name=n;}Void display (){System.out.println(rollno+” “+name” “+college);}public static void main(String[ ] args){student8 s1=new student8(228,”mahnoor”);student8 s2=new student8(051,”sana”);s1.display();s2.display();}

Page 29: Inheritance Slides

Why java main method is static ?

Because object is not required to call static method if it were non-static method, JVM create object first then call main() method that will lead the problem of extra memory allocation.

FINAL KEYWORD IN JAVAIT is used in java to restrict the user. It can be use in many contexts.VariableMethodClass

Page 30: Inheritance Slides

JAVA FINAL KEYWORD Stop change value Stop method overriding Stop inheritance

class Bike{final void run(){System.out.println(“running”);}class Honda extends Bike{void run(){System.out.println(“running safetly”);}Public static void main(String[ ] args){Honda honda= new Honda();Honda.run();}}

Page 31: Inheritance Slides

THAN

K YO

U!!