INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.

Slides:



Advertisements
Similar presentations
1 Classes and Objects in Java Basics of Classes in Java.
Advertisements

Object Oriented Programming with Java
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Java Programming Abstract classes and Interfaces.
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Exercise 1 Suppose C is a class that implements interfaces I and J. Which of the following Requires a type cast? C c = ……? I i = …..? J j = …..? c =
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Computer Science 209 Software Development Equality and Comparisons.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Overloading vs. Overriding b Don't confuse the concepts of overloading and overriding b Overloading deals with multiple methods in the same class with.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4 slides created by Marty Stepp
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Building Java Programs Interfaces, Comparable reading: , 16.4, 10.2.
UML Basics & Access Modifier
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Object Oriented Programming: Java Edition By: Samuel Robinson.
10/7/2015IT 1791 Java’s World in UML Object Shape {abstract} This is done implicitly Shape {abstract} - ShapeName: String # setShapeName(newShapeName:
1 Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy Invoking Superclass Methods.
CIS 644 Aug. 25, 1999 tour of Java. First … about the media lectures… we are experimenting with the media format please give feedback.
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Computer Science 209 Software Development Java Collections.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Interfaces and Inner Classes
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
1 Interfaces and Abstract Classes The ability to define the behavior of an object without specifying that behavior is to be implemented Interface class.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Building Java Programs Interfaces reading: , 16.4.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Web Design & Development Lecture 9
Interface.
Chapter 11: Inheritance and Polymorphism
Interfaces Professor Evan Korth.
Wrapper Classes ints, doubles, and chars are known as primitive types, or built-in types. There are no methods associated with these types of variables.
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Interface.
The Building Blocks Classes: Java class library, over 1,800 classes:
Implementing Non-Static Features
Interfaces.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Chapter 14 Abstract Classes and Interfaces
Creating and Modifying Text part 3
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need interfaces when we want functionality to be included but does not want to impose implementation. 3.Implementation issue is left to the individual classes implementing the interfaces. 4.Interfaces can have only abstract methods and final fields. 5.You can declare a variable to be of type interface. But you can not create an object belonging to type interface. 6.Interface variable can point to objects of any class implementing the interface. 7.Another way of implementing Run Time Polymorphism.

Similarities between Interfaces and classes is compiled into byte code file can be either public,protected, private or package accessibility can not be public unless defined in the file having same name as interface name serve as a type for declaring variables and parameters

Differences between Interfaces and classes Declares only method headers and public constants Has no constructors Can be implemented by a class Can not extend a class Can extend several other interfaces

General Form Syntax : interface extends [, ……] { [public][final] variablename 1 = value; …………………………………………. [public][final] variablename N = value; [public][abstract] methodname 1( ); [public][abstract] methodname 2( ); ………………………………………………………………………… [public][abstract] methodname N( ); }

Examples public interface A { double PI = ; void show(); void display(); } By Default public final Should be initialized double PI;  Wrong Should be typed in file A.java Can have only abstract methods. Each method is by default public abstract class XYZ implements A { public void show() { ….. } public void display() { ….. } }

interface A { int a=10; void show(); } interface B { int b=10; void print(); } interface C extends A,B { void display(); } AB C > Interfaces Can Extend Multiple Interfaces Interface Can not Extend a Class

Interfaces from Java’s Collection Framework Collection Set List Sorted Set Abstractcollection AbstractList > AbstractSequentialList LinkedList ArrayList Either a class should fully implement an interface or it should be declared as abstract

Interface Example interface Area { double PI = ; double area(); double perimeter(); } interface Volume extends Area { double volume(); } Area Volume

class Circle implements Area { private double radius; Circle(double radius) { this.radius = radius; } double getRadius() { return radius;} public double area() { return PI * radius * radius; } public double perimeter() { return 2 * PI * radius; } } Area Circle >

class BOX implements Volume { private double length; private double width; private double height; BOX(double l, double b, double h) { length = l; width = b; height = h; } double getLength() { return length ;} double getWidth() { return width ;} double getHeight() { return height ;} public double area() { return 2 * (length * width + width * height + height * length); } public double volume() { return length * width * height ; } public double perimeter() { return 4*(length + width + height); } } Volume BOX >

Comparable Interface 1.Provides an interface for comparing any two objects of same class. 2.General Form : public interface Comparable { int compareTo(Object other ); } Note : other parameter should be type casted to the class type implementing Comparable interface 3. Collections. sort method can sort objects of any class that implements comparable interface. 4. By implementing this interface, programmers can implement the logic for comparing two objects of same class for less than, greater than or equal to. public interface Comparable { int compareTo( other ); }

Examples for Implementation class BOX Implements Comparable { ……………………………………… public int compareTo(Object other) { BOX box = (BOX) other;......Logic for comparison …. } …………………………………. } class Student Implements Comparable { ……………………………………… public int compareTo(Object other) { Student std = (Student) other;......Logic for comparison …. } …………………………………. }

Examples for Implementation class BOX Implements Comparable { ……………………………………… public int compareTo(BOX other) {......Logic for comparison …. } …………………………………. } class Student Implements Comparable { ……………………………………… public int compareTo(Student other) {......Logic for comparison …. } …………………………………. }

Examples class BOX implements Comparable { private double length; private double width; private double height; BOX(double l,double b,double h) { length=l;width=b;height=h; } public double getLength() { return length;} public double getWidth() { return width;} public double getHeight() { return height;} public double getArea() { return 2*(length*width + width*height+height*length); } public double getVolume() { return length*width*height; } Unparametrized Comparable

public int compareTo(Object other) { BOX b1 =(BOX) other; if(this.getVolume() > b1.getVolume()) return 1; if(this.getVolume() < b1.getVolume()) return -1; return 0; } public String toString() { return “Length:”+length+” Width :”+width +” Height :”+height; } } // End of BOX class

import java.util.*; class ComparableTest { public static void main(String[] args) { BOX[] box = new BOX[5]; box[0] = new BOX(10,8,6); box[1] = new BOX(5,10,5); box[2] = new BOX(8,8,8); box[3] = new BOX(10,20,30); box[4] = new BOX(1,2,3); Arrays.sort(box); for(int i=0;i<box.length;i++) System.out.println(box[i]); } } // End of class Import java.util.*; class ComparableTest { public static void main(String[] args) { ArrayList box = new ArrayList(); box.add( new BOX(10,8,6)); box.add( new BOX(5,10,5)); box.add( new BOX(8,8,8)); box.add( new BOX(10,20,30)); box.add( new BOX(1,2,3)); Collections.sort(box); Iterator itr = ar.iterator(); while(itr.hasNext()) { BOX b =(BOX) itr.next(); System.out.println(b); } } }// End of class

Problems With Comparable Interface Method int compareTo(Object obj) needs to be included in the base class itself. We can include only single ordering logic. Different order requires logic to be included and requires changes in the base class itself. Each type we need different order we need to change the code itself.

import java.util.*; class Student implements Comparable { private String name; private String idno; private int age; private String city; …………………….. ……………………… public int compareTo(Object other) { Student std = (Student) other; return this.name.compareTo(other.name); } public String toString() { Return “Name:”+name+”Id No:”+idno+”Age:”+age; } } // End of class Student[] students = new Student[10]; …………………………… ………………………… ……………………………… Arrays.sort(students); for(int i=0 ; i<students.length;i++) System.out.println(students[i]); OUTPUT List sorted by Name

import java.util.*; class Student implements Comparable { private String name; private String idno; private int age; private String city; …………………….. ……………………… public int compareTo(Object other) { Student std = (Student) other; return this.idno.compareTo(other.idno); } public String toString() { Return “Name:”+name+”Id No:”+idno+”Age:”+age; } } // End of class Student[] students = new Student[10]; …………………………… ………………………… ……………………………… Arrays.sort(students); for(int i=0 ; i<students.length;i++) System.out.println(students[i]); OUTPUT List sorted by IdNo

Comparator Interface Allows two objects to compare explicitly. Syntax : public interface Comparator { int compare(Object O1, Object O2); } public interface Comparator { int compare(T O1, T O2); } Does not require change in the base class. We can define as many comparator classes for the base class. Each Comparator class implements Comparator interface and provides different logic for comparisons of objects. But as we are passing both parameters explicitly, we have to type cast both Object types to their base type before implementing the logic OR Use the second form Unparametrized Comparator Parametrized Comparator

Student class Student { private String name; private String idno; private int age; private String city; ………………….. Comparator studentbynamestudentbyidno studentbynameidnostudentbynameage studentbyage

class studentbyname implements comparator { public int compare(Object o1,Object o2) { Student s1 = (Student) o1; Student s2 = (Student) o2; return s1.getName().compareTo(s2.getName()); } } class studentbyidno implements comparator { public int compare(Object o1,Object o2) { Student s1 = (Student) o1; Student s2 = (Student) o2; return s1.getIdNo().compareTo(s2.getIdNo()); } }

class studentbyage implements comparator { public int compare(Object o1,Object o2) { Student s1 = (Student) o1; Student s2 = (Student) o2; if( s1.getAge() > s2.getAge() ) return 1; if( s1.getAge() < s2.getAge() ) return -1; return 0; } class studentbynameidno implements comparator { public int compare(Object o1,Object o2) { Student s1 = (Student) o1; Student s2 = (Student) o2; if( s1.getName().compareTo(s2.getName()) == 0) return s1.getIdNo().compareTo(s2.getIdNo()); else return s1.getName().compareTo(s2.getName()); }

class studentbynameage implements comparator { public int compare(Object o1,Object o2) { Student s1 = (Student) o1; Student s2 = (Student) o2; if( s1.getName().compareTo(s2.getName()) == 0) return s1.getAge() – s2.getAge(); else return s1.getName().compareTo(s2.getName()); }

Import java.util.*; class comparatorTest { public static void main(String args[]) { Student[] students = new Student[5]; Student[0] = new Student(“John”,”2000A1Ps234”,23,”Pilani”); Student[1] = new Student(“Meera”,”2001A1Ps234”,23,”Pilani”); Student[2] = new Student(“Kamal”,”2001A1Ps344”,23,”Pilani”); Student[3] = new Student(“Ram”,”2000A2Ps644”,23,”Pilani”); Student[4] = new Student(“Sham”,”2000A7Ps543”,23,”Pilani”); // Sort By Name Comparator c1 = new studentbyname(); Arrays.sort(students,c1); for(int i=0;i<students.length;i++) System.out.println(students[i]);

// Sort By Idno c1 = new studentbyidno(); Arrays.sort(students,c1); for(int i=0;i<students.length;i++) System.out.println(students[i]); // Sort By Age c1 = new studentbyage(); Arrays.sort(students,c1); for(int i=0;i<students.length;i++) System.out.println(students[i]); // Sort by Name & Idno c1 = new studentbynameidno(); Arrays.sort(students,c1); for(int i=0;i<students.length;i++) System.out.println(students[i]); // Sort by Name & Age c1 = new studentbynameage(); Arrays.sort(students,c1); for(int i=0;i<students.length;i++) System.out.println(students[i]); } // End of Main } // End of test class.