SlideShare a Scribd company logo
IMPLEMENTATION OF
INHERITANCE
       IN JAVA AND C#
INHERITANCE..

   As the name suggests, inheritance means to take something that is
    already made.
    It is one of the most important feature of Object Oriented
    Programming.
    It is the concept that is used for reusability purpose.
    Inheritance is the mechanism through which we can derived
    classes from other classes.
   The derived class is called as child class or the subclass or we can
    say the extended class and the class from which we are deriving the
    subclass is called the base class or the parent class.
TYPES OF INHERITANCE
       The following kinds of inheritance are there in java.
   Simple Inheritance
   Multilevel Inheritance
   Hierarchical inheritance
   Use case of Interfaces (Multiple,Hybrid Inheritance)
INHERITANCE
Simple Inheritance
    When a subclass is derived simply from it's parent class
then this mechanism is known as simple inheritance.
Multilevel Inheritance
 The process of a subclass is derived from a derived class.

 In multilevel, one-to-one ladder increases.

 Multiple classes are involved in inheritance, but one class
   extends only one.
 The lowermost subclass can make use of all its super classes'
   members.
INHERITANCE
Hierarchical Inheritance
 In hierarchical type of inheritance, one class is extended by many
  subclasses.
 It is one-to-many relationship.

Multiple Inheritance
 The process of more than one subclass is derived from a same
  base class.
 In multiple, many-to-one ladder increases.

 Multiple classes are involved in inheritance, but one class extends
  only one.
INHERITANCE

   Hybrid Inheritance
      Hybrid Inheritance is the combination of
    multiple, hierarchical inheritance.
IMPLEMENTATION OF INHERITANCE IN
JAVA
INHERITANCE IN JAVA
 To know about the concept of inheritance in java we should know
about the following concepts,
methods,

     data members,

     access controls,

     constructors,

     Key words

          ‘ this ’,
         ‘ super ‘etc.
To derive a class in java the keyword extends is used.
‘SUPER’ KEYWORD
.
    As the name suggest super is used to access the members of the
    super class.
    It is used for two purposes in java.
    1. The first use of keyword super is to access the hidden data
    variables of the super class hidden by the sub class.
     e.g. Suppose class A is the super class that has two instance
          variables as int a and float b.
          class B is the subclass that also contains its own data
     members named a and b.
           Then we can access the super class (class A) variables a and
     b inside the subclass class B just by calling the following
     command.
                          super.member;
CONT..
    2.Use of super to call super class constructor: The second
    use of the keyword super in java is to call super class
    constructor in the subclass.
         This functionality can be achieved just by using the
    following command.
                super(param-list);
   Here parameter list is the list of the parameter requires by the
    constructor in the super class.
   super must be the first statement executed inside a super class
    constructor.
    If we want to call the default constructor then we pass the
    empty parameter list.
‘THIS’ KEYWORD
   The keyword ’this’ is useful when we need to refer to instance of
    the class from its method.
   ‘this’ keyword helps us to avoid name conflicts.
   As we can see in the program that we have declare the name of
    instance variable and local variables same.
   The keyword this will reference the current class the word appears
    in.
    It will allow you to use the classes methods if used like this
                   this.methodName();
ACCESS SPECIFIERS IN JAVA
There are four Access Specifiers in Java
 1. Public: When a member of a class is declared as public
 specifier, it can be accessed from any code.

 2. Protected: Protected is only applicable in case of
 Inheritance. When a member of a class is declared as
 protected, it can only be accessed by the members of its class
 or subclass.

 3. Private: A member of a class is declared as private
 specifier, can only be accessed by the member of its class.

 4. Default: When you don't specify a access specifier to a
 member, Java automatically specifies a default. And the
 members modified by default can only be accessed by any
 other code in the package, but can't be accessed outside of a
 package.
AN EXAMPLE OF MULTI LEVEL INHERITANCE

   A Scenario where one class is inheriting/extending the behaviour
    of another class which in turn is inheriting behavior from yet
    another class.

    Ex: public class Automobile {…}
    Public class Car extends Automobile {…}
    Public class Ferrari extends Car {…}

    This multilevel inheritance actually has no limitations on the
    number of levels it can go.
   So as far as java goes, it is limitless. But for maintenance and ease
    of use sakes it is better to keep the inheritance levels to a single
    digit number.
EXAMPLE:

class Aves
 {                                                                 Aves
          public void nature() {
                   System.out.println(”Aves fly"); }
}                                                                   Bird
 class Bird extends Aves
{
                                                                   Parrot
          public void eat(){
                   System.out.println("Eats to live"); }
}
 class Parrot extends Bird
 {
          public void food() {
                   System.out.println("Parrot eats seeds andfruits"); }
CONT..

public static void main(String args[])
{
       Parrot p1 = new Parrot();
       p1.food(); // calling its own
       p1.eat();     // calling super class Bird
                            method
      p1.nature(); // calling super      class Aves
                            method
}
}
HOW TO DO MULTIPLE INHERITANCE IN JAVA?

  Actually, java does not support multiple inheritance

 However, you can achieve partial multiple inheritance with the
 help of interfaces.

 Ex: public class FerrariF12011 extends Ferrari implements Car,
 Automobile {…}

 And this is under the assumption that Car and Automobile are
 interfaces.
INTERFACES IN JAVA
   An interface is a container of abstract methods.
    It allows Java to implement Multiple Inheritance, because a class
    can't have more than one superclass in Java, but can implements
    many interfaces.
   Methods are just declared in interface, but not defined. The class
    which implements an interface must have to define the method
    declared in the interface.
   Access modifiers and return type must be same as declared in the
    interface.
   Private and static methods can't be declared in the interface.
WHY DOESN'T JAVA ALLOW MULTIPLE
INHERITANCE?
 Let us say the Automobile Class has a drive() method and the Car
class has a drive() method and the Ferrari class has a drive()
method too.
 Let us say we create a new class FerrariF12011 that looks like
below:
Public class FerrariF12011 extends Ferrari, Car, Automobile {…}

And at some point of time we need to call the drive() method, what
would happen?
Our JVM wouldn't know which method to invoke and we may have
to instantiate one of the classes that you already inherit in order to
call its appropriate method.
 To avoid this why the creators of java did not include this direct
multiple inheritance feature.
EXAMPLE
interface Suzuki
{                                          Suzuki            Ford
        public abstract void body();
 }
interface Ford
 {                                                MotorCar
        public abstract void engine();
 }
public class MotorCar implements Suzuki, Ford
{
        public void body()
        {
                System.out.println("Fit Suzuki body");
        }
CONT..

      public void engine()
      {
             System.out.println("Fit Ford engine");
      }
public static void main(String args[]) {
       MotorCar mc1 = new MotorCar();
      mc1.body();
      mc1.engine();
}}
How it works???
      In the above code there are two interfaces – Suzuki and
Ford.
Both are implemented by MotorCar because it would like to
have the features of both interfaces
 Just to inform there are multiple interfaces and not classes,
  tell the compiler by replacing "extends" with "implements”.
 MotorCar, after implementing both the interfaces, overrides
  the abstract methods of the both – body() and engine(); else
  program does not compile.
‘FINAL’ KEYWORD
   It can also be called as Restricting Inheritance
   Classes that cant be extended are called final classes.
   We use the final modifier in the definition of the class to
    indicate this.
        final class myclass
        {
               // Insert code here
        }
IMPLEMENTATION OF INHERITANCE IN C#
INHERITANCE IN C#
        Syntax for deriving a class from a base class
class Token
{          Derived class Base class
    ...
}
class CommentToken: Token
{
    ...            Colon
}
        A derived class inherits most elements of its
         base class
        A derived class cannot be more accessible
         than its base class
CALLING BASE CLASS CONSTRUCTORS
        Constructor declarations must use the base keyword
class Token
{
    protected Token(string name) { ... }
    ...
}
class CommentToken: Token
{
    public CommentToken(string name) : base(name) { }
     A private base class constructor cannot be accessed by a
    ...derived class
}    Use the base keyword to qualify identifier scope
DEFINING VIRTUAL METHODS
      Syntax: Declare as virtual
class Token
{
    ...
    public int LineNumber( )
    { ...
    }
    public virtual string Name( )
    { ...
    }
}     Virtual methods are polymorphic
OVERRIDING METHODS

   Syntax: Use the override keyword

    class Token
    {   ...
        public virtual string Name( ) { ... }
    }
    class CommentToken: Token
    {   ...
        public override string Name( ) { ... }
    }
WORKING WITH OVERRIDE METHODS
  You can only override identical inherited virtual methods
 class Token
 {   ...
     public int LineNumber( ) { ... }
     public virtual string Name( ) { ... }
 }
 class CommentToken: Token

                                                           
 {   ...
     public override int LineNumber( ) { ... }

 }
     public override string Name( ) { ... }
                                                          
     You must match an override method with its associated virtual
      method
     You can override an override method
     You cannot explicitly declare an override method as virtual
     You cannot declare an override method as static or private
USING NEW TO HIDE METHODS

   Syntax: Use the new keyword to hide a
    method
    class Token
    {   ...
        public int LineNumber( ) { ... }
    }
    class CommentToken: Token
    {   ...
        new public int LineNumber( ) { ... }

    }
WORKING WITH THE NEW KEYWORD
   Hide both virtual and non-virtual methods
class Token
{   ...
    public int LineNumber( ) { ... }
    public virtual string Name( ) { ... }
}
class CommentToken: Token
{   ...
    new public int LineNumber( ) { ... }
    public override string Name( ) { ... }
}


 Resolve name clashes in code
 Hide methods that have identical signatures
MULTI LEVEL INHERITANCE

 Multi Level Inheritance is supported in C#.
 Any level of inheritance is possible to inherit
  a class “:” is used after the class name.
 Like „super‟ keyword in Java, here we have
  „base‟ keyword which can be used during
  header initialization.
 It will invoke the immediate base class of the
  calling class.
SAMPLE PROGRAM
class person
   {
     string name;                                 Person
     int age;
     public person()
     {
        Console.Write("Enter Name : ");          Employee
        name = Console.ReadLine();
        Console.Write("Enter age : ");
        age = Convert.ToInt32(Console.Read());   Program
     }
     public virtual void put_data()
     {
        Console.Write("Name : " + name);
        Console.Write("Age : " + age);
     }
   }
CONT..
class employee : person
  {
    int salary;
    public employee()
    {
       Console.Write("Enter Salary : ");
       salary = Convert.ToInt32(Console.Read);
    }
    public override void put_data()
    {
       Console.Write("Salary : " + salary);
    }
  }
CONT..
class Program : employee
   {
     static void Main(string[] args)
     {
        employee e1 = new employee();
        e1.put_data();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();

      }
  }
MULTIPLE INHERITANCE

 Like Java C# does‟nt have multiple
  inheritance.
 The reason is same that of java.

 We can perform that through interfaces we
  can implement any number of interfaces.
DECLARING INTERFACES


                                            Interface names should
                                             begin with a capital “I”


interface IToken
                                                   IToken
{
                                                « interface »
    int LineNumber( );
    string Name( );                          LineNumber( )
}                                            Name( )

  No access specifiers   No method bodies
IMPLEMENTING MULTIPLE INTERFACES
       A class can implement zero or more interfaces


interface IToken
{
    string Name( );             IToken           IVisitable
}                            « interface »     « interface »
interface IVisitable
{
    void Accept(IVisitor v);
}
class Token: IToken, IVisitable
{ ...                                      Token
}

       An interface can extend zero or more interfaces
       A class can be more accessible than its base interfaces
       An interface cannot be more accessible than its base
        interfaces
       A class must implement all inherited interface methods
IMPLEMENTING INTERFACE METHODS
   The implementing method must be the same as the
    interface method
   The implementing method can be virtual or non-
    virtual
                                       Same access
class Token: IToken, IVisitable        Same return type
{                                      Same name
    public virtual string Name( )      Same parameters
    { ...
    }
    public void Accept(IVisitor v)
    { ...
    }
}
THANK YOU

More Related Content

What's hot

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
sivasundari6
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
javaicon
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
Kurapati Vishwak
 
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cyclemyrajendra
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
Iqra khalil
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
Nilesh Dalvi
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
Arnab Bhaumik
 

What's hot (20)

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Java threads
Java threadsJava threads
Java threads
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
OOP java
OOP javaOOP java
OOP java
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Inheritance
InheritanceInheritance
Inheritance
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 

Viewers also liked

Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Arati Gadgil
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
Rosie Jane Enomar
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
cprogrammings
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Laxman Puri
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
Muraleedhar Sundararajan
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
kamal kotecha
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
Atul Sehdev
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
M. Raihan
 
5.interface and packages
5.interface and packages5.interface and packages
5.interface and packagesDeepak Sharma
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
Vinod Kumar
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Veerabadra Badra
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
OUM SAOKOSAL
 
Learn java objects inheritance-overriding-polymorphism
Learn java objects  inheritance-overriding-polymorphismLearn java objects  inheritance-overriding-polymorphism
Learn java objects inheritance-overriding-polymorphism
TOPS Technologies
 

Viewers also liked (20)

Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
Interface
InterfaceInterface
Interface
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
5.interface and packages
5.interface and packages5.interface and packages
5.interface and packages
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
 
Learn java objects inheritance-overriding-polymorphism
Learn java objects  inheritance-overriding-polymorphismLearn java objects  inheritance-overriding-polymorphism
Learn java objects inheritance-overriding-polymorphism
 

Similar to Inheritance in java

SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
JayMistry91473
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
venud11
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
talha ijaz
 
some basic knowledge about Java programming
some basic knowledge about Java programming some basic knowledge about Java programming
some basic knowledge about Java programming
ITTraining2
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
chetanpatilcp783
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
kristinatemen
 
Java features
Java featuresJava features
Java features
Prashant Gajendra
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Ayes Chinmay
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
Shubham Sharma
 
INHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptxINHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptx
NITHISG1
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
siragezeynu
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
G C Reddy Technologies
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
Gaurav Mehta
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 

Similar to Inheritance in java (20)

SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
some basic knowledge about Java programming
some basic knowledge about Java programming some basic knowledge about Java programming
some basic knowledge about Java programming
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
Java features
Java featuresJava features
Java features
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
Java 06
Java 06Java 06
Java 06
 
INHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptxINHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptx
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 

More from Tech_MX

Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimationTech_MX
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
String & its application
String & its applicationString & its application
String & its applicationTech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application Tech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applicationsTech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2Tech_MX
 
Set data structure
Set data structure Set data structure
Set data structure Tech_MX
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating SystemTech_MX
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Tech_MX
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pcTech_MX
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbmsTech_MX
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)Tech_MX
 
Memory dbms
Memory dbmsMemory dbms
Memory dbmsTech_MX
 

More from Tech_MX (20)

Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Uid
UidUid
Uid
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
String & its application
String & its applicationString & its application
String & its application
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Spss
SpssSpss
Spss
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
 
Set data structure
Set data structure Set data structure
Set data structure
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
 
Parsing
ParsingParsing
Parsing
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
 
More on Lex
More on LexMore on Lex
More on Lex
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
 

Recently uploaded

Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 

Recently uploaded (20)

Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 

Inheritance in java

  • 2. INHERITANCE..  As the name suggests, inheritance means to take something that is already made.  It is one of the most important feature of Object Oriented Programming.  It is the concept that is used for reusability purpose.  Inheritance is the mechanism through which we can derived classes from other classes.  The derived class is called as child class or the subclass or we can say the extended class and the class from which we are deriving the subclass is called the base class or the parent class.
  • 3. TYPES OF INHERITANCE The following kinds of inheritance are there in java.  Simple Inheritance  Multilevel Inheritance  Hierarchical inheritance  Use case of Interfaces (Multiple,Hybrid Inheritance)
  • 4. INHERITANCE Simple Inheritance When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. Multilevel Inheritance  The process of a subclass is derived from a derived class.  In multilevel, one-to-one ladder increases.  Multiple classes are involved in inheritance, but one class extends only one.  The lowermost subclass can make use of all its super classes' members.
  • 5. INHERITANCE Hierarchical Inheritance  In hierarchical type of inheritance, one class is extended by many subclasses.  It is one-to-many relationship. Multiple Inheritance  The process of more than one subclass is derived from a same base class.  In multiple, many-to-one ladder increases.  Multiple classes are involved in inheritance, but one class extends only one.
  • 6. INHERITANCE  Hybrid Inheritance Hybrid Inheritance is the combination of multiple, hierarchical inheritance.
  • 8. INHERITANCE IN JAVA To know about the concept of inheritance in java we should know about the following concepts, methods,  data members,  access controls,  constructors,  Key words ‘ this ’, ‘ super ‘etc. To derive a class in java the keyword extends is used.
  • 9. ‘SUPER’ KEYWORD . As the name suggest super is used to access the members of the super class. It is used for two purposes in java. 1. The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class. e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. Then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command. super.member;
  • 10. CONT.. 2.Use of super to call super class constructor: The second use of the keyword super in java is to call super class constructor in the subclass. This functionality can be achieved just by using the following command. super(param-list);  Here parameter list is the list of the parameter requires by the constructor in the super class.  super must be the first statement executed inside a super class constructor.  If we want to call the default constructor then we pass the empty parameter list.
  • 11. ‘THIS’ KEYWORD  The keyword ’this’ is useful when we need to refer to instance of the class from its method.  ‘this’ keyword helps us to avoid name conflicts.  As we can see in the program that we have declare the name of instance variable and local variables same.  The keyword this will reference the current class the word appears in.  It will allow you to use the classes methods if used like this this.methodName();
  • 12. ACCESS SPECIFIERS IN JAVA There are four Access Specifiers in Java 1. Public: When a member of a class is declared as public specifier, it can be accessed from any code. 2. Protected: Protected is only applicable in case of Inheritance. When a member of a class is declared as protected, it can only be accessed by the members of its class or subclass. 3. Private: A member of a class is declared as private specifier, can only be accessed by the member of its class. 4. Default: When you don't specify a access specifier to a member, Java automatically specifies a default. And the members modified by default can only be accessed by any other code in the package, but can't be accessed outside of a package.
  • 13. AN EXAMPLE OF MULTI LEVEL INHERITANCE  A Scenario where one class is inheriting/extending the behaviour of another class which in turn is inheriting behavior from yet another class. Ex: public class Automobile {…} Public class Car extends Automobile {…} Public class Ferrari extends Car {…} This multilevel inheritance actually has no limitations on the number of levels it can go.  So as far as java goes, it is limitless. But for maintenance and ease of use sakes it is better to keep the inheritance levels to a single digit number.
  • 14. EXAMPLE: class Aves { Aves public void nature() { System.out.println(”Aves fly"); } } Bird class Bird extends Aves { Parrot public void eat(){ System.out.println("Eats to live"); } } class Parrot extends Bird { public void food() { System.out.println("Parrot eats seeds andfruits"); }
  • 15. CONT.. public static void main(String args[]) { Parrot p1 = new Parrot(); p1.food(); // calling its own p1.eat(); // calling super class Bird method p1.nature(); // calling super class Aves method } }
  • 16. HOW TO DO MULTIPLE INHERITANCE IN JAVA? Actually, java does not support multiple inheritance However, you can achieve partial multiple inheritance with the help of interfaces. Ex: public class FerrariF12011 extends Ferrari implements Car, Automobile {…} And this is under the assumption that Car and Automobile are interfaces.
  • 17. INTERFACES IN JAVA  An interface is a container of abstract methods.  It allows Java to implement Multiple Inheritance, because a class can't have more than one superclass in Java, but can implements many interfaces.  Methods are just declared in interface, but not defined. The class which implements an interface must have to define the method declared in the interface.  Access modifiers and return type must be same as declared in the interface.  Private and static methods can't be declared in the interface.
  • 18. WHY DOESN'T JAVA ALLOW MULTIPLE INHERITANCE? Let us say the Automobile Class has a drive() method and the Car class has a drive() method and the Ferrari class has a drive() method too. Let us say we create a new class FerrariF12011 that looks like below: Public class FerrariF12011 extends Ferrari, Car, Automobile {…} And at some point of time we need to call the drive() method, what would happen? Our JVM wouldn't know which method to invoke and we may have to instantiate one of the classes that you already inherit in order to call its appropriate method. To avoid this why the creators of java did not include this direct multiple inheritance feature.
  • 19. EXAMPLE interface Suzuki { Suzuki Ford public abstract void body(); } interface Ford { MotorCar public abstract void engine(); } public class MotorCar implements Suzuki, Ford { public void body() { System.out.println("Fit Suzuki body"); }
  • 20. CONT.. public void engine() { System.out.println("Fit Ford engine"); } public static void main(String args[]) { MotorCar mc1 = new MotorCar(); mc1.body(); mc1.engine(); }}
  • 21. How it works??? In the above code there are two interfaces – Suzuki and Ford. Both are implemented by MotorCar because it would like to have the features of both interfaces  Just to inform there are multiple interfaces and not classes, tell the compiler by replacing "extends" with "implements”.  MotorCar, after implementing both the interfaces, overrides the abstract methods of the both – body() and engine(); else program does not compile.
  • 22. ‘FINAL’ KEYWORD  It can also be called as Restricting Inheritance  Classes that cant be extended are called final classes.  We use the final modifier in the definition of the class to indicate this. final class myclass { // Insert code here }
  • 24. INHERITANCE IN C#  Syntax for deriving a class from a base class class Token { Derived class Base class ... } class CommentToken: Token { ... Colon }  A derived class inherits most elements of its base class  A derived class cannot be more accessible than its base class
  • 25. CALLING BASE CLASS CONSTRUCTORS  Constructor declarations must use the base keyword class Token { protected Token(string name) { ... } ... } class CommentToken: Token { public CommentToken(string name) : base(name) { }  A private base class constructor cannot be accessed by a ...derived class }  Use the base keyword to qualify identifier scope
  • 26. DEFINING VIRTUAL METHODS  Syntax: Declare as virtual class Token { ... public int LineNumber( ) { ... } public virtual string Name( ) { ... } }  Virtual methods are polymorphic
  • 27. OVERRIDING METHODS  Syntax: Use the override keyword class Token { ... public virtual string Name( ) { ... } } class CommentToken: Token { ... public override string Name( ) { ... } }
  • 28. WORKING WITH OVERRIDE METHODS You can only override identical inherited virtual methods class Token { ... public int LineNumber( ) { ... } public virtual string Name( ) { ... } } class CommentToken: Token  { ... public override int LineNumber( ) { ... } } public override string Name( ) { ... }   You must match an override method with its associated virtual method  You can override an override method  You cannot explicitly declare an override method as virtual  You cannot declare an override method as static or private
  • 29. USING NEW TO HIDE METHODS  Syntax: Use the new keyword to hide a method class Token { ... public int LineNumber( ) { ... } } class CommentToken: Token { ... new public int LineNumber( ) { ... } }
  • 30. WORKING WITH THE NEW KEYWORD  Hide both virtual and non-virtual methods class Token { ... public int LineNumber( ) { ... } public virtual string Name( ) { ... } } class CommentToken: Token { ... new public int LineNumber( ) { ... } public override string Name( ) { ... } }  Resolve name clashes in code  Hide methods that have identical signatures
  • 31. MULTI LEVEL INHERITANCE  Multi Level Inheritance is supported in C#.  Any level of inheritance is possible to inherit a class “:” is used after the class name.  Like „super‟ keyword in Java, here we have „base‟ keyword which can be used during header initialization.  It will invoke the immediate base class of the calling class.
  • 32. SAMPLE PROGRAM class person { string name; Person int age; public person() { Console.Write("Enter Name : "); Employee name = Console.ReadLine(); Console.Write("Enter age : "); age = Convert.ToInt32(Console.Read()); Program } public virtual void put_data() { Console.Write("Name : " + name); Console.Write("Age : " + age); } }
  • 33. CONT.. class employee : person { int salary; public employee() { Console.Write("Enter Salary : "); salary = Convert.ToInt32(Console.Read); } public override void put_data() { Console.Write("Salary : " + salary); } }
  • 34. CONT.. class Program : employee { static void Main(string[] args) { employee e1 = new employee(); e1.put_data(); Console.WriteLine("Press any key to exit..."); Console.ReadLine(); } }
  • 35. MULTIPLE INHERITANCE  Like Java C# does‟nt have multiple inheritance.  The reason is same that of java.  We can perform that through interfaces we can implement any number of interfaces.
  • 36. DECLARING INTERFACES Interface names should begin with a capital “I” interface IToken IToken { « interface » int LineNumber( ); string Name( ); LineNumber( ) } Name( ) No access specifiers No method bodies
  • 37. IMPLEMENTING MULTIPLE INTERFACES  A class can implement zero or more interfaces interface IToken { string Name( ); IToken IVisitable } « interface » « interface » interface IVisitable { void Accept(IVisitor v); } class Token: IToken, IVisitable { ... Token }  An interface can extend zero or more interfaces  A class can be more accessible than its base interfaces  An interface cannot be more accessible than its base interfaces  A class must implement all inherited interface methods
  • 38. IMPLEMENTING INTERFACE METHODS  The implementing method must be the same as the interface method  The implementing method can be virtual or non- virtual Same access class Token: IToken, IVisitable Same return type { Same name public virtual string Name( ) Same parameters { ... } public void Accept(IVisitor v) { ... } }