SlideShare uma empresa Scribd logo
1 de 44
Baixar para ler offline
Abstract Class &
 Java Interface

                   1
Agenda
●   What is an Abstract method and an Abstract class?
●   What is Interface?
●   Why Interface?
●   Interface as a Type
●   Interface vs. Class
●   Defining an Interface
●   Implementing an Interface
●   Implementing multiple Interface's
●   Inheritance among Interface's
●   Interface and Polymorphism
●   Rewriting an Interface                          2
What is
an Abstract Class?
                     3
Abstract Methods
●   Methods that do not have implementation (body)
●   To create an abstract method, just write the method
    declaration without the body and use the abstract
    keyword
    –   No { }

●   For example,

        // Note that there is no body
        public abstract void someMethod();



                                                          4
Abstract Class

●   An abstract class is a class that contains one or
    more abstract methods
●   An abstract class cannot instantiated
    // You will get a compile error on the following code
    MyAbstractClass a1 = new MyAbstractClass();
●   Another class (Concrete class) has to provide
    implementation of abstract methods
    –   Concrete class has to implement all abstract methods of
        the abstract class in order to be used for instantiation
    –   Concrete class uses extends keyword

                                                                   5
Sample Abstract Class
public abstract class LivingThing {
   public void breath(){
      System.out.println("Living Thing breathing...");
   }

    public void eat(){
       System.out.println("Living Thing eating...");
    }

    /**
     * Abstract method walk()
     * We want this method to be implemented by a
     * Concrete class.
     */
    public abstract void walk();
}

                                                         6
Extending an Abstract Class
●   When a concrete class extends the LivingThing
    abstract class, it must implement the abstract
    method walk(), or else, that subclass will also
    become an abstract class, and therefore cannot be
    instantiated.

●   For example,
    public class Human extends LivingThing {

        public void walk(){
           System.out.println("Human walks...");
        }

    }                                                   7
When to use Abstract Methods &
           Abstract Class?
●   Abstract methods are usually declared where two
    or more subclasses are expected to fulfill a similar
    role in different ways through different
    implementations
    –   These subclasses extend the same Abstract class and
        provide different implementations for the abstract
        methods
●   Use abstract classes to define broad types of
    behaviors at the top of an object-oriented
    programming class hierarchy, and use its
    subclasses to provide implementation details of the
    abstract class.
                                                              8
What is Interface?

                     9
What is an Interface?

●   It defines a standard and public way of specifying
    the behavior of classes
    –   Defines a contract
●   All methods of an interface are abstract methods
    –   Defines the signatures of a set of methods, without the
        body (implementation of the methods)
●   A concrete class must implement the interface (all
    the abstract methods of the Interface)
●   It allows classes, regardless of their locations in the
    class hierarchy, to implement common behaviors

                                                                  10
Example: Interface


// Note that Interface contains just set of method
// signatures without any implementations.
// No need to say abstract modifier for each method
// since it assumed.
public interface Relation {
      public boolean isGreater( Object a, Object b);
      public boolean isLess( Object a, Object b);
      public boolean isEqual( Object a, Object b);
}



                                                       11
Example 2: OperatorCar Interface

public interface OperateCar {

    // constant declarations, if any

    // method signatures
    int turn(Direction direction,
        double radius, double startSpeed, double endSpeed);
    int changeLanes(Direction direction, double startSpeed,
                     double endSpeed);
    int signalTurn(Direction direction, boolean signalOn);
    int getRadarFront(double distanceToCar,
                      double speedOfCar);
    int getRadarRear(double distanceToCar,
                      double speedOfCar);
          ......
    // more method signatures
}
                                                         12
Why Interface?

                 13
Why do we use Interfaces?
               Reason #1
●   To reveal an object's programming interface
    (functionality of the object) without revealing its
    implementation
    –   This is the concept of encapsulation
    –   The implementation can change without affecting
        the caller of the interface
    –   The caller does not need the implementation at the
        compile time
         ●   It needs only the interface at the compile time
         ●   During runtime, actual object instance is associated
             with the interface type
                                                                    14
Why do we use Interfaces?
               Reason #2
●   To have unrelated classes implement similar
    methods (behaviors)
    –   One class is not a sub-class of another
●   Example:
    –   Class Line and class MyInteger
         ● They are not related through inheritance
         ● You want both to implement comparison methods


             – checkIsGreater(Object x, Object y)
             – checkIsLess(Object x, Object y)
             – checkIsEqual(Object x, Object y)
    –   Define Comparison interface which has the three
        abstract methods above                             15
Why do we use Interfaces?
               Reason #3
●   To model multiple inheritance
    –   A class can implement multiple interfaces while it can
        extend only one class




                                                                 16
Interface vs. Abstract Class

●   All methods of an Interface are abstract methods
    while some methods of an Abstract class are
    abstract methods
    –   Abstract methods of abstract class have abstract
        modifier
●   An interface can only define constants while
    abstract class can have fields
●   Interfaces have no direct inherited relationship with
    any particular class, they are defined independently
    –   Interfaces themselves have inheritance relationship
        among themselves
                                                              17
Interface as a
    Type
                 18
Interface as a Type

●   When you define a new interface, you are defining a
    new reference type
●   You can use interface names anywhere you can use
    any other type name
●   If you define a reference variable whose type is an
    interface, any object you assign to it must be an
    instance of a class that implements the interface




                                                          19
Example: Interface as a Type

●   Let's say Person class implements PersonInterface
    interface
●   You can do
     –   Person p1 = new Person();
     –   PersonInterface pi1 = p1;
     –   PersonInterface pi2 = new Person();




                                                        20
Interface vs. Class

                      21
Interface vs. Class: Commonality

●   Interfaces and classes are both types
    –   This means that an interface can be used in places
        where a class can be used
    –   For example:
         // Recommended practice
         PersonInterface     pi = new Person();
         // Not recommended practice
         Person        pc = new Person();
●   Interface and Class can both define methods



                                                             22
Interface vs. Class: Differences

●   The methods of an Interface are all abstract
    methods
    –   They cannot have bodies
●   You cannot create an instance from an interface
    –   For example:
         PersonInterface   pi = new PersonInterface(); //ERROR!
●   An interface can only be implemented by classes or
    extended by other interfaces



                                                                  23
Defining Interface

                     24
Defining Interfaces

●   To define an interface, we write:

    public interface [InterfaceName] {
          //some methods without the body
    }




                                            25
Defining Interfaces
●   As an example, let's create an interface that defines
    relationships between two objects according to the
    “natural order” of the objects.

    public interface Relation {
        public boolean isGreater( Object a, Object b);
        public boolean isLess( Object a, Object b);
        public boolean isEqual( Object a, Object b);
    }




                                                            26
Implementing
  Interface
               27
Implementing Interfaces
●   To create a concrete class that implements an interface,
    use the implements keyword.
    /**
     * Line class implements Relation interface
     */
    public class Line implements Relation {
          private double x1;
          private double x2;
          private double y1;
          private double y2;

          public Line(double x1, double x2, double y1, double y2){
              this.x1 = x1;
              this.x2 = x2;
              this.y1 = y1;
              this.y2 = y2;
          }

         // More code follows                                        28
Implementing Interfaces
public double getLength(){
       double length = Math.sqrt((x2-x1)*(x2-x1) +
                      (y2-y1)* (y2-y1));
       return length;
    }

    public boolean isGreater( Object a, Object b){
        double aLen = ((Line)a).getLength();
        double bLen = ((Line)b).getLength();
        return (aLen > bLen);
    }

    public boolean isLess( Object a, Object b){
        double aLen = ((Line)a).getLength();
        double bLen = ((Line)b).getLength();
        return (aLen < bLen);

    }

    public boolean isEqual( Object a, Object b){
        double aLen = ((Line)a).getLength();
        double bLen = ((Line)b).getLength();
        return (aLen == bLen);
    }
}
                                                     29
Implementing Interfaces
●   When your class tries to implement an interface,
    always make sure that you implement all the
    methods of that interface, or else, you would
    encounter this error,

    Line.java:4: Line is not abstract and does not override
      abstract method
      isGreater(java.lang.Object,java.lang.Object) in Relation
    public class Line implements Relation
          ^
    1 error



                                                                 30
Implementing Class
●   Implementing class can have its own methods
●   Implementing class extend a single super class or
    abstract class




                                                        31
Implementing
Multiple Interfaces
                      32
Relationship of an Interface to a
                 Class
●   A concrete class can only extend one super class,
    but it can implement multiple Interfaces
    –   The Java programming language does not permit
        multiple inheritance (inheritance is discussed later in
        this lesson), but interfaces provide an alternative.
●   All abstract methods of all interfaces have to be
    implemented by the concrete class




                                                                  33
Example: Implementing Multiple
              Interfaces
●   A concrete class extends one super class but
    multiple Interfaces:

    public class ComputerScienceStudent
                   extends Student
                   implements PersonInterface,
                              AnotherInterface,
                              Thirdinterface{

        // All abstract methods of all interfaces
        // need to be implemented.
    }



                                                    34
Inheritance
Among Interfaces
                   35
Inheritance Among Interfaces

●   Interfaces are not part of the class hierarchy
●   However, interfaces can have inheritance
    relationship among themselves


    public interface PersonInterface {
       void doSomething();
    }

    public interface StudentInterface
                     extends PersonInterface {
       void doExtraSomething();
    }


                                                     36
Interface &
Polymorphism
               37
Interface and Polymorphism

●   Interfaces exhibit polymorphism as well, since
    program may call an interface method, and the
    proper version of that method will be executed
    depending on the type of object instance passed to
    the interface method call




                                                         38
Rewriting Interfaces

                       39
Problem of Rewriting an Existing
                Interface
●   Consider an interface that you have developed called DoIt:
         public interface DoIt {
           void doSomething(int i, double x);
           int doSomethingElse(String s);
         }
●   Suppose that, at a later time, you want to add a third method to
    DoIt, so that the interface now becomes:
          public interface DoIt {
            void doSomething(int i, double x);
            int doSomethingElse(String s);
            boolean didItWork(int i, double x, String s);
          }
●   If you make this change, all classes that implement the old DoIt
    interface will break because they don't implement all methods of
    the the interface anymore
                                                                  40
Solution of Rewriting an Existing
                 Interface
●   Create more interfaces later
●   For example, you could create a DoItPlus interface that
    extends DoIt:
    public interface DoItPlus extends DoIt {
      boolean didItWork(int i, double x, String s);
    }
●   Now users of your code can choose to continue to use
    the old interface or to upgrade to the new interface




                                                        41
When to Use an
Abstract Class over
   an Interface?
                      42
When to use an Abstract Class
           over Interface?
●   For non-abstract methods, you want to use them
    when you want to provide common implementation
    code for all sub-classes
    –   Reducing the duplication
●   For abstract methods, the motivation is the same
    with the ones in the interface – to impose a
    common behavior for all sub-classes without
    dictating how to implement it
●   Remember a concrete can extend only one super
    class whether that super class is in the form of
    concrete class or abstract class
                                                       43
Abstract Class &
 Java Interface

                   44

Mais conteúdo relacionado

Mais procurados

Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaEdureka!
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & InterfaceLinh Lê
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
 
Abstract class and interface
Abstract class and interfaceAbstract class and interface
Abstract class and interfaceMazharul Sabbir
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and InterfaceHaris Bin Zahid
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
Interfaces In Java
Interfaces In JavaInterfaces In Java
Interfaces In Javaparag
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaMOHIT AGARWAL
 

Mais procurados (20)

Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Abstract class and interface
Abstract class and interfaceAbstract class and interface
Abstract class and interface
 
Abstract class
Abstract classAbstract class
Abstract class
 
Java interface
Java interfaceJava interface
Java interface
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Abstract method
Abstract methodAbstract method
Abstract method
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Interfaces In Java
Interfaces In JavaInterfaces In Java
Interfaces In Java
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java interface
Java interfaceJava interface
Java interface
 

Destaque

Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentationtigerwarn
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming ConceptsMohamed Emam
 
4 abstract class, interface
4 abstract class, interface4 abstract class, interface
4 abstract class, interfaceRobbie AkaChopa
 
Abstrac tinheritance polymorphism
Abstrac tinheritance polymorphismAbstrac tinheritance polymorphism
Abstrac tinheritance polymorphismHoang Nguyen
 
Java (Netbeans) - Abstract & Interface - Object Oriented Programming
Java (Netbeans) - Abstract & Interface - Object Oriented ProgrammingJava (Netbeans) - Abstract & Interface - Object Oriented Programming
Java (Netbeans) - Abstract & Interface - Object Oriented ProgrammingMelina Krisnawati
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in javasawarkar17
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsClint Edmonson
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 
Android app development - Java Programming for Android
Android app development - Java Programming for AndroidAndroid app development - Java Programming for Android
Android app development - Java Programming for AndroidOUM SAOKOSAL
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsRaja Sekhar
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract ClassOUM SAOKOSAL
 
LinkedIn SlideShare: Knowledge, Well-Presented
LinkedIn SlideShare: Knowledge, Well-PresentedLinkedIn SlideShare: Knowledge, Well-Presented
LinkedIn SlideShare: Knowledge, Well-PresentedSlideShare
 

Destaque (17)

Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
4 abstract class, interface
4 abstract class, interface4 abstract class, interface
4 abstract class, interface
 
Abstrac tinheritance polymorphism
Abstrac tinheritance polymorphismAbstrac tinheritance polymorphism
Abstrac tinheritance polymorphism
 
Java (Netbeans) - Abstract & Interface - Object Oriented Programming
Java (Netbeans) - Abstract & Interface - Object Oriented ProgrammingJava (Netbeans) - Abstract & Interface - Object Oriented Programming
Java (Netbeans) - Abstract & Interface - Object Oriented Programming
 
Concept of Object Oriented Programming
Concept of Object Oriented Programming Concept of Object Oriented Programming
Concept of Object Oriented Programming
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Interesting Concept of Object Oriented Programming
Interesting Concept of Object Oriented Programming Interesting Concept of Object Oriented Programming
Interesting Concept of Object Oriented Programming
 
Advanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, IdiomsAdvanced OOP - Laws, Principles, Idioms
Advanced OOP - Laws, Principles, Idioms
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Android app development - Java Programming for Android
Android app development - Java Programming for AndroidAndroid app development - Java Programming for Android
Android app development - Java Programming for Android
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwords
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
 
LinkedIn SlideShare: Knowledge, Well-Presented
LinkedIn SlideShare: Knowledge, Well-PresentedLinkedIn SlideShare: Knowledge, Well-Presented
LinkedIn SlideShare: Knowledge, Well-Presented
 

Semelhante a javainterface

Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Advanced Programming _Abstract Classes vs Interfaces (Java)
Advanced Programming _Abstract Classes vs Interfaces (Java)Advanced Programming _Abstract Classes vs Interfaces (Java)
Advanced Programming _Abstract Classes vs Interfaces (Java)Professor Lili Saghafi
 
Corejavainterviewquestions.doc
Corejavainterviewquestions.docCorejavainterviewquestions.doc
Corejavainterviewquestions.docJoyce Thomas
 
Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and InterfacesJamsher bhanbhro
 
12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.pptVISHNUSHANKARSINGH3
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oopcolleges
 
EEE oops Vth semester viva questions with answer
EEE oops Vth semester viva questions with answerEEE oops Vth semester viva questions with answer
EEE oops Vth semester viva questions with answerJeba Moses
 
What are abstract classes Dont interfaces also allow for polymo.pdf
What are abstract classes Dont interfaces also allow for polymo.pdfWhat are abstract classes Dont interfaces also allow for polymo.pdf
What are abstract classes Dont interfaces also allow for polymo.pdfarihantkitchenmart
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interfacemanish kumar
 

Semelhante a javainterface (20)

Interfaces
InterfacesInterfaces
Interfaces
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Interface
InterfaceInterface
Interface
 
Advanced Programming _Abstract Classes vs Interfaces (Java)
Advanced Programming _Abstract Classes vs Interfaces (Java)Advanced Programming _Abstract Classes vs Interfaces (Java)
Advanced Programming _Abstract Classes vs Interfaces (Java)
 
Corejavainterviewquestions.doc
Corejavainterviewquestions.docCorejavainterviewquestions.doc
Corejavainterviewquestions.doc
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and Interfaces
 
Interfaces
InterfacesInterfaces
Interfaces
 
Bai giang-uml-11feb14
Bai giang-uml-11feb14Bai giang-uml-11feb14
Bai giang-uml-11feb14
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt12.2 Abstract class and Interface.ppt
12.2 Abstract class and Interface.ppt
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Interface &amp;packages
Interface &amp;packagesInterface &amp;packages
Interface &amp;packages
 
EEE oops Vth semester viva questions with answer
EEE oops Vth semester viva questions with answerEEE oops Vth semester viva questions with answer
EEE oops Vth semester viva questions with answer
 
Java interface
Java interface Java interface
Java interface
 
What are abstract classes Dont interfaces also allow for polymo.pdf
What are abstract classes Dont interfaces also allow for polymo.pdfWhat are abstract classes Dont interfaces also allow for polymo.pdf
What are abstract classes Dont interfaces also allow for polymo.pdf
 
04 inheritance
04 inheritance04 inheritance
04 inheritance
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
Core java questions
Core java questionsCore java questions
Core java questions
 

Mais de Arjun Shanka (20)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
javainheritance
javainheritancejavainheritance
javainheritance
 
javarmi
javarmijavarmi
javarmi
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
hibernate
hibernatehibernate
hibernate
 
javapackage
javapackagejavapackage
javapackage
 
javaarray
javaarrayjavaarray
javaarray
 
swingbasics
swingbasicsswingbasics
swingbasics
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
struts
strutsstruts
struts
 
javathreads
javathreadsjavathreads
javathreads
 
javabeans
javabeansjavabeans
javabeans
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
javaiostream
javaiostreamjavaiostream
javaiostream
 

Último

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Último (20)

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

javainterface

  • 1. Abstract Class & Java Interface 1
  • 2. Agenda ● What is an Abstract method and an Abstract class? ● What is Interface? ● Why Interface? ● Interface as a Type ● Interface vs. Class ● Defining an Interface ● Implementing an Interface ● Implementing multiple Interface's ● Inheritance among Interface's ● Interface and Polymorphism ● Rewriting an Interface 2
  • 4. Abstract Methods ● Methods that do not have implementation (body) ● To create an abstract method, just write the method declaration without the body and use the abstract keyword – No { } ● For example, // Note that there is no body public abstract void someMethod(); 4
  • 5. Abstract Class ● An abstract class is a class that contains one or more abstract methods ● An abstract class cannot instantiated // You will get a compile error on the following code MyAbstractClass a1 = new MyAbstractClass(); ● Another class (Concrete class) has to provide implementation of abstract methods – Concrete class has to implement all abstract methods of the abstract class in order to be used for instantiation – Concrete class uses extends keyword 5
  • 6. Sample Abstract Class public abstract class LivingThing { public void breath(){ System.out.println("Living Thing breathing..."); } public void eat(){ System.out.println("Living Thing eating..."); } /** * Abstract method walk() * We want this method to be implemented by a * Concrete class. */ public abstract void walk(); } 6
  • 7. Extending an Abstract Class ● When a concrete class extends the LivingThing abstract class, it must implement the abstract method walk(), or else, that subclass will also become an abstract class, and therefore cannot be instantiated. ● For example, public class Human extends LivingThing { public void walk(){ System.out.println("Human walks..."); } } 7
  • 8. When to use Abstract Methods & Abstract Class? ● Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations – These subclasses extend the same Abstract class and provide different implementations for the abstract methods ● Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class. 8
  • 10. What is an Interface? ● It defines a standard and public way of specifying the behavior of classes – Defines a contract ● All methods of an interface are abstract methods – Defines the signatures of a set of methods, without the body (implementation of the methods) ● A concrete class must implement the interface (all the abstract methods of the Interface) ● It allows classes, regardless of their locations in the class hierarchy, to implement common behaviors 10
  • 11. Example: Interface // Note that Interface contains just set of method // signatures without any implementations. // No need to say abstract modifier for each method // since it assumed. public interface Relation { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); } 11
  • 12. Example 2: OperatorCar Interface public interface OperateCar { // constant declarations, if any // method signatures int turn(Direction direction, double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); ...... // more method signatures } 12
  • 14. Why do we use Interfaces? Reason #1 ● To reveal an object's programming interface (functionality of the object) without revealing its implementation – This is the concept of encapsulation – The implementation can change without affecting the caller of the interface – The caller does not need the implementation at the compile time ● It needs only the interface at the compile time ● During runtime, actual object instance is associated with the interface type 14
  • 15. Why do we use Interfaces? Reason #2 ● To have unrelated classes implement similar methods (behaviors) – One class is not a sub-class of another ● Example: – Class Line and class MyInteger ● They are not related through inheritance ● You want both to implement comparison methods – checkIsGreater(Object x, Object y) – checkIsLess(Object x, Object y) – checkIsEqual(Object x, Object y) – Define Comparison interface which has the three abstract methods above 15
  • 16. Why do we use Interfaces? Reason #3 ● To model multiple inheritance – A class can implement multiple interfaces while it can extend only one class 16
  • 17. Interface vs. Abstract Class ● All methods of an Interface are abstract methods while some methods of an Abstract class are abstract methods – Abstract methods of abstract class have abstract modifier ● An interface can only define constants while abstract class can have fields ● Interfaces have no direct inherited relationship with any particular class, they are defined independently – Interfaces themselves have inheritance relationship among themselves 17
  • 18. Interface as a Type 18
  • 19. Interface as a Type ● When you define a new interface, you are defining a new reference type ● You can use interface names anywhere you can use any other type name ● If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface 19
  • 20. Example: Interface as a Type ● Let's say Person class implements PersonInterface interface ● You can do – Person p1 = new Person(); – PersonInterface pi1 = p1; – PersonInterface pi2 = new Person(); 20
  • 22. Interface vs. Class: Commonality ● Interfaces and classes are both types – This means that an interface can be used in places where a class can be used – For example: // Recommended practice PersonInterface pi = new Person(); // Not recommended practice Person pc = new Person(); ● Interface and Class can both define methods 22
  • 23. Interface vs. Class: Differences ● The methods of an Interface are all abstract methods – They cannot have bodies ● You cannot create an instance from an interface – For example: PersonInterface pi = new PersonInterface(); //ERROR! ● An interface can only be implemented by classes or extended by other interfaces 23
  • 25. Defining Interfaces ● To define an interface, we write: public interface [InterfaceName] { //some methods without the body } 25
  • 26. Defining Interfaces ● As an example, let's create an interface that defines relationships between two objects according to the “natural order” of the objects. public interface Relation { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); } 26
  • 28. Implementing Interfaces ● To create a concrete class that implements an interface, use the implements keyword. /** * Line class implements Relation interface */ public class Line implements Relation { private double x1; private double x2; private double y1; private double y2; public Line(double x1, double x2, double y1, double y2){ this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } // More code follows 28
  • 29. Implementing Interfaces public double getLength(){ double length = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)* (y2-y1)); return length; } public boolean isGreater( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen > bLen); } public boolean isLess( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen < bLen); } public boolean isEqual( Object a, Object b){ double aLen = ((Line)a).getLength(); double bLen = ((Line)b).getLength(); return (aLen == bLen); } } 29
  • 30. Implementing Interfaces ● When your class tries to implement an interface, always make sure that you implement all the methods of that interface, or else, you would encounter this error, Line.java:4: Line is not abstract and does not override abstract method isGreater(java.lang.Object,java.lang.Object) in Relation public class Line implements Relation ^ 1 error 30
  • 31. Implementing Class ● Implementing class can have its own methods ● Implementing class extend a single super class or abstract class 31
  • 33. Relationship of an Interface to a Class ● A concrete class can only extend one super class, but it can implement multiple Interfaces – The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative. ● All abstract methods of all interfaces have to be implemented by the concrete class 33
  • 34. Example: Implementing Multiple Interfaces ● A concrete class extends one super class but multiple Interfaces: public class ComputerScienceStudent extends Student implements PersonInterface, AnotherInterface, Thirdinterface{ // All abstract methods of all interfaces // need to be implemented. } 34
  • 36. Inheritance Among Interfaces ● Interfaces are not part of the class hierarchy ● However, interfaces can have inheritance relationship among themselves public interface PersonInterface { void doSomething(); } public interface StudentInterface extends PersonInterface { void doExtraSomething(); } 36
  • 38. Interface and Polymorphism ● Interfaces exhibit polymorphism as well, since program may call an interface method, and the proper version of that method will be executed depending on the type of object instance passed to the interface method call 38
  • 40. Problem of Rewriting an Existing Interface ● Consider an interface that you have developed called DoIt: public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); } ● Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes: public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); boolean didItWork(int i, double x, String s); } ● If you make this change, all classes that implement the old DoIt interface will break because they don't implement all methods of the the interface anymore 40
  • 41. Solution of Rewriting an Existing Interface ● Create more interfaces later ● For example, you could create a DoItPlus interface that extends DoIt: public interface DoItPlus extends DoIt { boolean didItWork(int i, double x, String s); } ● Now users of your code can choose to continue to use the old interface or to upgrade to the new interface 41
  • 42. When to Use an Abstract Class over an Interface? 42
  • 43. When to use an Abstract Class over Interface? ● For non-abstract methods, you want to use them when you want to provide common implementation code for all sub-classes – Reducing the duplication ● For abstract methods, the motivation is the same with the ones in the interface – to impose a common behavior for all sub-classes without dictating how to implement it ● Remember a concrete can extend only one super class whether that super class is in the form of concrete class or abstract class 43
  • 44. Abstract Class & Java Interface 44