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 =

Slides:



Advertisements
Similar presentations
Basic Java Constructs and Data Types – Nuts and Bolts
Advertisements

11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Interfaces (Part II) Course Lecture Slides 28 June 2010 A picture is.
Building Java Programs Chapter 10
The ArrayList Class and the enum Keyword
The List ADT Textbook Sections
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
The Point Class public class Point { public double x; public double y; public Point(double x0, double y0) { x = x0; y = y0; } public double distance(Point.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
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.
Inheritance // A simple class hierarchy. // A class for two-dimensional objects. class TwoDShape { double width; double height; void showDim() { System.out.println("Width.
Interfaces CSC 171 FALL 2004 LECTURE 14. Project 1 review public class Rational { private int numerator, denominator; public Rational(int numerator, int.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
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.
Java Review Interface, Casting, Generics, Iterator.
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.
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.
Strings in Java 1. strings in java are handled by two classes String &
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Written by: Dr. JJ Shepherd
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
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.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Arrays And ArrayLists - S. Kelly-Bootle
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Effective Java: Generics Last Updated: Spring 2009.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Arrays of Objects 1 Fall 2012 CS2302: Programming Principles.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
CSC 205 Programming II Lecture 18 The Eight Queens Problem.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Types in programming languages1 What are types, and why do we need them?
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
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.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Computer Science 209 Software Development Inheritance and Composition.
Iteration Abstraction SWE Software Construction Fall 2009.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Object Oriented Programming Lecture 2: BallWorld.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
The AP Java Subset Topics. A Topics Primitive Types int double boolean.
Methods Attributes Method Modifiers ‘static’
Iteration Abstraction
null, true, and false are also reserved.
CSE 1030: Implementing Non-Static Features
ITI Introduction to Computing II Lab-12
TCSS 143, Autumn 2004 Lecture Notes
Agenda Types and identifiers Practice Assignment Keywords in Java
CMPE212 – Reminders Assignment 2 due next Friday.
CSC 205 Java Programming II
Presentation transcript:

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 = i j = c i = j C I J << class>> << interfaces>> c = (C) i

Exercise 2 Suppose C is a class that implements interfaces I and J. Which of the following will throw an Exception? C c = new C() I i = c; J j = (J) i; C d = (C) i; C I J << class>> << interfaces>>

Exercise 3 Suppose the class Sandwich implements Editable interface. Which if the following statements are legal? Sandwich sub = new Sandwich(); Editable e = sub; sub = e sub = (Sandwich) e; OK OK Illegal OK << interfaces>> Editable Sandwich << class>>

Write classes Implementing the Area and Volume Interface Interface Area { double PI = 3.14; double area(); } Area Interface Volume { double volume(); } Volume Rectangle Triangle Circle BOX << Implements both Area and Volume interface>> << Implements only Area interface>>

Cont… class Rectangle implements Area { …………………… ……………………. public double area() ….. } ……… …….. class circle implements Area { …………………… ……………………. public double area() ….. } ……… …….. class BOX implements Area , Volume { …………………… ……………………. public double area() { …..} public double volume() {……} } << Implement the methods from interface with public scope>>

public static void main(String args[]) Exception in thread "main" java.lang.ClassCastException: A at java.util.Arrays.mergeSort(Arrays.java:1156) at java.util.Arrays.sort(Arrays.java:1080) at ctest.main(ctest.java:21) import java.util.*; class A { int a; } class ctest { public static void main(String args[]) String[] names = {"OOP","BITS","PILANI"}; Arrays.sort(names); int[] data = { 10,-45,87,0,20,21 }; Arrays.sort(data); A[] arr = new A[5]; arr[0] = new A(); arr[1] = new A(); arr[2] = new A(); arr[3] = new A(); arr[4] = new A(); Arrays.sort(arr); } } Ok As String class implements Comparable Ok As Integer class implements Comparable NOT Ok as A class does not implements Comparable.

Unparametrized Comparator import java.util.*; class A implements Comparable { int a; public int compareTo(Object other) A a1 = (A) other; if(this.a == a1.a ) return 0; if(this.a < a1.a ) return -1; return 1; } class ctest { public static void main(String args[]) String[] names = {"OOP","BITS","PILANI"}; Arrays.sort(names); int[] data = { 10,-45,87,0,20,21 }; Arrays.sort(data); A[] arr = new A[5]; arr[0] = new A(); arr[1] = new A(); arr[2] = new A(); arr[3] = new A(); arr[4] = new A(); Arrays.sort(arr); } Will Work Will Work Type cast Object type to Base Type Before use Will Work Unparametrized Comparable

Parametrized Comparator import java.util.*; class A implements Comparable<A> { int a; public int compareTo(A other) // A a1 = (A) other; //No need of cast if(this.a == other.a ) return 0; if(this.a < other.a ) return -1; return 1; } class ctest { public static void main(String args[]) String[] names = {"OOP","BITS","PILANI"}; Arrays.sort(names); int[] data = { 10,-45,87,0,20,21 }; Arrays.sort(data); A[] arr = new A[5]; arr[0] = new A(); arr[1] = new A(); arr[2] = new A(); arr[3] = new A(); arr[4] = new A(); Arrays.sort(arr); } Will Work Will Work Parametrized Comparable Will Work

class BOX implements Comparable<BOX> { private double l,b,h; import java.util.*; class BOX implements Comparable<BOX> { private double l,b,h; // Overloaded Constructors BOX(double a) { l=b=h=a; } BOX(double l,double b,double h) { this.l=l; this.b=b; this.h=h; // Acessor Methods public double getL() { return l; public double getB() { return b; public double getH() { return h; Parametrized Comparable of type BOX Cont….

// area() Volume() Methods double area() { return 2*(l*b+b*h+h*l); } double volume() return l*b*h; // isEquals() method boolean isEqual(BOX other) if(this.area() == other.area()) return true; return false; /* OR if(area() == other.area()) return true */ static boolean isEquals(BOX b1, BOX b2) if(b1.area() == b2.area()) return true;

// compareTo method public int compareTo(BOX other) { if(area() > other.area()) return 1; if(area() < other.area()) return -1; return 0; } public String toString() String s1="length:"+l; String s2="width:"+b; String s3="area:"+h; String s4="Area:"+area(); String s5="Volume:"+volume(); return s1+s2+s3+s4+s5; } // End of class BOX

class comparableTest10 { public static void main(String args[]) ArrayList<BOX> boxes = new ArrayList<BOX>(); boxes.add(new BOX(10)); boxes.add(new BOX(20)); boxes.add(new BOX(10,6,8)); boxes.add(new BOX(4,6,10)); boxes.add(new BOX(10,12,14)); Iterator itr = boxes.iterator(); while(itr.hasNext()) System.out.println((BOX)itr.next()); Collections.sort(boxes); Iterator itr1 = boxes.iterator(); while(itr1.hasNext()) System.out.println((BOX)itr1.next()); }

Converting a Class To an Interface Type Interface acts as a super class for the implementation classes. A reference variable belonging to type interface can point to any of the object of the classes implementing the interface. A B C X << classes >> << interface >> A a1 = new A(); X x1 = a1; Class to interface type Conversion

Converting an Interface to a class Type X x1 = new A(); A a1 = (A) x1; X x1 = new B(); B b1 = (B) x1; X x1 = new C(); C c1 = (C) x1; A B C X << classes >> << interface >> Interface to Class type Conversion

Comparator Example Supply comparators for BOX class so that BOX[] OR ArrayList<BOX> can be sorted by any of the following orders: Sort By Length Either in Ascending or descending order Sort By Width Either in Ascending or descending order Sort By Height Either in Ascending or descending order Sort By Area Either in Ascending or descending order Sort By Volume Either in Ascending or descending order

Comparator<BOX> BOX is base class whose references stored either in Arrays or in Any Collection class such as ArrayList, Vector or LinkedList Needs to be sorted class BOX { ……………….instance fields ………………instance methods …………………… } Comparator<BOX> SORTBOXBYLENGTH SORTBOXBYWIDTH SORTBOXBYHEIGHT SORTBOXBYAREA SORTBOXBYVOLUME BOX class does not implement any comparable or comparatorinterface Comparator Classes

import java.util.*; class BOX { private double l,b,h; // Overloaded Constructors BOX(double a) { l=b=h=a; } BOX(double l,double b,double h) this.l=l; this.b=b; this.h=h; // Acessor Methods public double getL() { return l; public double getB() { return b; public double getH() { return h; // area() Volume() Methods double area() { return 2*(l*b+b*h+h*l); } double volume() return l*b*h; // isEquals() method boolean isEqual(BOX other) if(this.area() == other.area()) return true; return false; /* OR if(area() == other.area()) return true */ Cont …..

static boolean isEquals(BOX b1, BOX b2) { if(b1.area() == b2.area()) return true; return false; } public String toString() String s1="length:"+l; String s2="width:"+b; String s3="area:"+h; String s4="Area:"+area(); String s5="Volume:"+volume(); return s1+s2+s3+s4+s5; } // End of class BOX NOTE : BOX class is base class whose references needs to be sorted. It does not implement either comparable or comparator class Cont …..

// Comparator class for Sorting by BOX references By length class SORTBOXBYLENGTH implements Comparator<BOX> { private int order; // Defines Order of sorting 1 for Ascending -1 for Descending SORTBOXBYLENGTH(boolean isAscending) if(isAscending) order =1; else order =-1; } public int compare(BOX b1,BOX b2) if(b1.getL() > b2.getL()) return 1*order; if(b1.getL() < b2.getL()) return -1*order; return 0; }// End of class

// Comparator class for Sorting by BOX references By Width class SORTBOXBYWIDTH implements Comparator<BOX> { private int order; SORTBOXBYWIDTH(boolean isAscending) if(isAscending) order =1; else order =-1; } public int compare(BOX b1,BOX b2) if(b1.getB() > b2.getB()) return 1*order; if(b1.getB() < b2.getB()) return -1*order; return 0; } // End of class

// Comparator class for Sorting by BOX references By Height class SORTBOXBYHEIGHT implements Comparator<BOX> { private int order; SORTBOXBYHEIGHT(boolean isAscending) if(isAscending) order =1; else order =-1; } public int compare(BOX b1,BOX b2) if(b1.getH() > b2.getH()) return 1*order; if(b1.getH() < b2.getH()) return -1*order; return 0; } // End of class

// Comparator class for Sorting by BOX references By Area class SORTBOXBYAREA implements Comparator<BOX> { private int order; SORTBOXBYAREA(boolean isAscending) if(isAscending) order =1; else order =-1; } public int compare(BOX b1,BOX b2) if(b1.area() > b2.area()) return 1*order; if(b1.area() < b2.area()) return -1*order; return 0; } // End of class

// Comparator class for Sorting by BOX references By Volume class SORTBOXBYVOLUME implements Comparator<BOX> { private int order; SORTBOXBYVOLUME(boolean isAscending) if(isAscending) order =1; else order =-1; } public int compare(BOX b1,BOX b2) if(b1.volume() > b2.volume()) return 1*order; if(b1.volume() < b2.volume()) return -1*order; return 0; } // End of class

ArrayList<BOX> boxes = new ArrayList<BOX>(); class comparatorTest { public static void main(String args[]) { ArrayList<BOX> boxes = new ArrayList<BOX>(); boxes.add(new BOX(10)); boxes.add(new BOX(20)); boxes.add(new BOX(10,6,8)); boxes.add(new BOX(4,6,10)); boxes.add(new BOX(10,12,14)); // SORT BY LENTH ORDER:Ascending Comparator<BOX> c1 = new SORTBOXBYLENGTH(true); Collections.sort(boxes,c1); for(int i=0;i<boxes.size();i++) System.out.println(boxes.get(i)); System.out.println(""); // SORT BY LENTH ORDER:Descending c1 = new SORTBOXBYLENGTH(false);

// SORT BY Volume ORDER:Ascending c1 = new SORTBOXBYVOLUME(true); Collections.sort(boxes,c1); for(int i=0;i<boxes.size();i++) System.out.println(boxes.get(i)); System.out.println(""); // SORT BY Volume ORDER:Descending c1 = new SORTBOXBYVOLUME(false); } } // End of Main class

OUTPUT length:4.0width:6.0area:10.0Area:248.0Volume:240.0