Module1.AnnotatedNotes.DataStructures.2024.pdf

Full Transcript

CSCI 2110 Data Structures and Algorithms CSCI 2110: Module 1 Srini Sampalli 1 OUR FIRST MODULE: A Painless Refresher on Object oriented programming REVIEW + CSCI 2110: Module 1 Srini Sampalli 2 What we will cover in thi...

CSCI 2110 Data Structures and Algorithms CSCI 2110: Module 1 Srini Sampalli 1 OUR FIRST MODULE: A Painless Refresher on Object oriented programming REVIEW + CSCI 2110: Module 1 Srini Sampalli 2 What we will cover in this module… Traditional vs. Object-oriented programming (OOP) Basics of OOP in Java The Class file à Defines an Object à Encapsulation Two useful entities: this parameter and the toString method Method Overloading Garbage Collection in Java Static methods and Static Variables CSCI 2110: Module 1 Srini Sampalli 3 What we will cover in this module… Inheritance The Object Class Abstract Classes and Interfaces Polymorphism Generics CSCI 2110: Module 1 Srini Sampalli 4 Traditional Programming Paradigms Memory Sequential programming (example - early BASIC) Main program instructions Only one main program with a sequence of instructions. Instructions directly operate on global data. Data Procedural Programming (examples – C, Pascal, FORTRAN) Main program Main program calls procedures or methods. instructions Control is returned to the main program once the Procedure1/ procedure is completed. Method1 Data is still global. Procedure2/ Method2 Data CSCI 2110: Module 1 Srini Sampalli 5 Some drawbacks of traditional programming Memory Does not model the real world. Main program instructions Inefficient coding. Data Problem with global data – any method could Main program access any data. This could lead to instructions programming errors. Procedure1/M ethod1 Procedure2/ Method2 Data CSCI 2110: Module 1 Srini Sampalli 6 Object 3 The Object-Oriented Approach Object 1 Data Key Idea: Encapsulate both data and methods into one Data Method1 software entity called an object. Method2 Method1 Each object carries its own data and can be acted upon by its own Method2 procedures/methods. Main (Client) Instructions § The program is a web of interacting objects. Object 2 § Objects interact with each other by sending messages (invoking Data operations on methods of other objects). § There is also a main program (called the client) that initiates the Method1 process. Method2 CSCI 2110: Module 1 Srini Sampalli 7 Examples of “objects” Geometry program – Rectangle object, Circle object, etc. Bank Account program – Bank Account object, Loan object Stock Purchase program – Stock object Simple car simulator – Start button, stop button, gas pedal, brake and steering wheel objects Alarm clock simulator – Number display objects, sound alarm object, button objects, etc. Course (database) – Student object, Instructor object, Textbook object CSCI 2110: Module 1 Srini Sampalli 8 Advantages of object-oriented programming Mirrors real-world applications. Each programming module (object) can be changed independent of the other modules à flexibility and scalability. Only allowed data (variables) and methods can be accessed by other modules à less error-prone. Each object can be modeled by an interface. The interface tells the outside world what the object has to offer and what it is capable of. A client can send a message to an interface with a guarantee that even if the object s implementation changes, client does not have to rewrite the code. CSCI 2110: Module 1 Srini Sampalli 9 The three pillars of object-oriented programming Encapsulation is just one of the important features of OOP. The other two are Inheritance and Polymorphism. Object Oriented Programming (OOP) Encapsulation Inheritance Polymorphism CSCI 2110: Module 1 Srini Sampalli 10 Basics of Object-oriented programming in Java Two basic steps: Define objects à ENCAPSULATION Create and use the objects We define an object in a class file: Fields/ Attributes to hold data à variable declarations (typically private) Procedures/Operations on the data à methods (typically public) CSCI 2110: Module 1 Srini Sampalli 11 A super-simple example (no objects – just a client program) public class Hello { public static void main(String[ ] args) { System.out.println(“Hello Virtual World!”); } } CSCI 2110: Module 1 Srini Sampalli 12 A super-simple example (no objects – just a client program) Every program in java This is the name of publicly accessible – must belong to a class the class file anyone can run this program Opening of the class body Name of this method public class Hello { (the main method is the entry point of any java program) Opening Other programs can run this method of the public static void main(String[ ] args) { method System.out.println(“Hello Virtual World!”); } Method closing Parameters passed } Class closing into the method (in This method belongs to this case, command This method line arguments as an the class, not an object does not return anything array of strings) Java statement that displays the argument passed; It calls the println CSCImethod 2110: Module– 1 from the java standard library Srini Sampalli 13 Let’s look at an object-oriented program with objects (0,0) (xpos, ypos) A Rectangle Object height width CSCI 2110: Module 1 Srini Sampalli 14 Code Example 1: A Basic Object Oriented Program public class Rectangle1{ private int xpos, ypos, width, height; constructor public Rectangle1(){ } public void setX(int x){ I 0 xpos = x; } public void setY(int y){ Is ypos = y; } set methods or public void setWidth(int w){ width = w; mutator methods } public void setHeight(int h){ height = h; } public int getX(){ return xpos; } public int getY(){ methods or return ypos; 9 accenor methods } public int getWidth(){ return width; } public int getHeight(){ return height; } public void moveTo(int x, int y){ xpos = x; ypos = y; } public void resize(int w, int h) other methods { width = w; height = h; } } public class Rectangle1Demo { public static void main(String[] args){ Rectangle1 rect1; declare I a Rectangle object rect1 = new Rectangle1(); rect1.setX(100); instantiate it rect1.setY(50); rect1.setWidth(20); methods rect1.setHeight(25); rect1.moveTo(200,300); call the rect1.resize(10,30); System.out.println("[" + rect1.getX()+","+rect1.getY()+"'"+"]" + "\twidth: " + rect1.getWidth() + "\theight: " + display rect1.getHeight()+"\n"); } } 14a Two useful entities: the keyword this and the toString method The keyword this: In the method public int setX(int x){xpos = x;} suppose that we want to use the same variable name xpos as the argument. This can be done by using the keyword this. this refers to the parameter of the current object and can be used to distinguish the instance variable from the method parameter. Thus: public int setX(int xpos){this.xpos = xpos;} CSCI 2110: Module 1 Srini Sampalli 15 Two useful entities: the keyword this and the toString method The toString method: Just gives the String representation of an object. We can design the toString method in order to print the object s attributes in whatever convenient form that we wish. For example, we can use it to print xpos, ypos, width and height of the rectangle object. The method header is public String toString() toString() can be ignored when calling the method. CSCI 2110: Module 1 Srini Sampalli 16 Code Example 2: Illustration of the ‘this’ parameter and ‘toString’ method public class Rectangle2{ private int xpos, ypos, width, height; public Rectangle2(){ } public void setX(int xpos){ this.xpos = xpos; } public void setY(int ypos){ this.ypos = ypos; } public void setWidth(int width){ this.width = width; } public void setHeight(int height){ this.height = height; } public int getX(){ return xpos; } public int getY(){ return ypos; } public int getWidth(){ return width; } public int getHeight(){ return height; } public void moveTo(int xpos, int ypos){ this.xpos = xpos; this.ypos = ypos; } public void resize(int width, int height){ this.width = width; this.height = height; } public String toString(){ return "["+ xpos + "," + ypos + "]" + "\t" + "width= " + width + "," "height= " + height; } public static void main(String[] args){ Rectangle2 rect1; rect1 = new Rectangle2(); rect1.setX(100); rect1.setY(50); rect1.setWidth(20); rect1.setHeight(25); System.out.println("Before modification: " + rect1); rect1.moveTo(200,300); rect1.resize(10,30); System.out.println("After modification: " + rect1); } } 1 a Method overloading Can two methods in a class have the same name? Yes – provided their signatures are different. What is the signature of a method? The signature of a method is the method s name, type and order of its input parameters. Return type is not part of the signature. Examples: resize(int, int) and setHeight(int) are the signatures of the resize and setHeight methods, respectively. When you write two or more methods with the same name in a class, it is called This method overloading and the methods are called overloaded methods. Method overloading is useful when we need several different ways to perform the same operation. Constructors can also be overloaded, which means that a class can have more than one constructor and eventually, more than one way of creating objects. CSCI 2110: Module 1 Srini Sampalli 17 Tryout Code Example 3: Method Overloading public class Rectangle3{ private int xpos, ypos, width, height; public Rectangle3(){ } //overloaded constructor pu lic ectangle int xpos, int ypos, int idth, int height this xpos xpos this ypos ypos this idth idth this height height //rest of the code same as Rectangle2.java //contains method: true if a point px, py is contained in this rectangle pu lic oolean contains int px, int py return px xpos px xpos idth py ypos py ypos height //contains method: true if another rectangle is contained in this rectangle pu lic oolean contains ectangle r return this contains r get , r get this contains r get r get idth , r get r get eight 1 a Tryout Code Example 3: Method Overloading public class Rectangle3{ private int xpos, ypos, width, height; public Rectangle3(){ } //overloaded constructor pu lic ectangle int xpos, int ypos, int idth, int height this xpos xpos this ypos ypos this idth idth this height height //rest of the code same as Rectangle2.java //contains method: true if a point px, py is contained in this rectangle pu lic oolean contains int px, int py return px xpos px xpos idth py ypos py ypos height //contains method: true if another rectangle is contained in this rectangle pu lic oolean contains ectangle r return this contains r get , r get this contains r get r get idth , r get r get eight // lient program ectangle rect ne ectangle , , , ectangle rect ne ectangle , , , ystem out println rect contains rect displays true ystem out println rect contains rect displays false 1 a Garbage Collection in Java The memory space occupied by an object is reclaimed by the garbage collector in java when the object is no longer in use. For example, suppose that in a program we write: Rectangle3 rect1 = new Rectangle3(100,50, 10, 20); …. rect1 = new Rectangle3(200, 50, 20, 30); The first rectangle which was created has no reference to it anymore. Thus it is not accessible anymore. Nullifying an object reference will also invoke the garbage collector to remove it: rect1 = null; Garbage collector always runs in the background, identifies objects without references, and reclaims the space used by the object. You can also request the garbage collector with the following statement in your program: System.gc(); CSCI 2110: Module 1 Srini Sampalli 18 STATIC METHODS AND VARIABLES Static Methods §A static method is one that can be used without an object. §Sometimes we may need methods that have no relation to an object of any kind. §Examples: § Method to determine the larger of two integers. § Method to compute the cube root of a number. § Method to convert temperature from Celsius to Fahrenheit. §Static methods are defined by writing the keyword static in the method header. CSCI 2110: Module 1 Srini Sampalli 19 Static Methods (cont d.) Static methods are still defined inside a class, but they can be invoked without creating an object. For example, you can create a collection of static methods to perform computations that are related and group them within a single class. You can also include static methods along with other non-static methods in a class. CSCI 2110: Module 1 Srini Sampalli 20 Calling a static method When you call a static method from outside the class, the class name is used if being invoked without an object: className.methodName(….parameters…) The class name can be ignored if the static method is called from within the same class. CSCI 2110: Module 1 Srini Sampalli 21 Examples of static methods main is a static method that can be included in any class. Another example of a class of static methods : Math class. (example usage: Math.pow(2.0,3.0), Math.random(5), etc.) Note: All the methods that are used in procedural programming are static methods. CSCI 2110: Module 1 Srini Sampalli 22 public class Temp{ public static double C2F(double c){ return (c*9.0/5.0 + 32.0); } public static double F2C(double f){ return ((f-32.0)*5.0/9.0); } public static void main(String[] args){ double ctemp, ftemp; ftemp = Temp.C2F(32.0); ctemp = Temp.F2C(100.0); } } CSCI 2110: Module 1 Srini Sampalli 23 Static Variables What is a static variable? When you write a class file, you can declare two kinds of variables: Instance variables Static variables Instance variable: Each object gets a separate version of this variable. Static variable: Only one copy exists. Individual objects do not get separate versions. CSCI 2110: Module 1 Srini Sampalli 24 public class SomeClass { private static int num1; private int num2; private int num3; num1 is a static variable num2 and num3 are instance variables SomeClass num1 object1 object2 num2 num2 num3 CSCI 2110: Module 1 Srini Sampalli num3 25 Rules for static methods and variables You can define a class with static variables and instance variables, static methods and non-static methods. A non-static method in a class can access both instance variables and static variables of the class. A non-static method in a class can invoke both static and non-static methods of the class. A static method in a class can access only static variables and static methods directly. It can access non-static variables and non-static methods only through objects. Constants are shared by all objects of the class. Thus, constants should be declared final static. For e.g., private final static double PI = 3.14159; CSCI 2110: Module 1 Srini Sampalli 26 Code Example 4: Static variables and methods The objective is to design a Bank Account class that has a combination of static variables, instance variables, static methods and non-static methods. Implement a BankAccount class with the following specifications: Instance variables name and balance Static variables interest rate and number of accounts, both set to 0. A constructor which sets the name and balance, and increments number of accounts. A static method to set the interest rate A static method to get the interest rate A static method to get the number of accounts A non-static method to deposit an amount A non-static method to withdraw an amount A non-static method to add interest A non-static method to get the balance. A non-static method to set the balance. A non-static method to transfer funds to another account. A non-static toString method Test the BankAccount class by creating five Bank Accounts, depositing amounts into each, adding interest , withdrawing amounts and transferring funds. Print the individual accounts as well as the static variable that indicates the number of accounts created. //BankAccount.java public class BankAccount{ private String name; private double balance; private static double rate = 0.0; private static int numAccounts = 0; public BankAccount(String n, double b){ name = n; balance = b; numAccounts++; } public static void setInterestRate(double r){ rate = r; } public static double getInterestRate(){ return rate; } public static int getNumAccounts(){ return numAccounts; } public void deposit(double amount){ if (amountbalance) System.out.println("Insufficient funds"); else a balance-=amount; } public void addInterest(){ double interest = balance*rate; balance+=interest; } public double getBalance(){ return balance; } public void setBalance(double amount){ balance +=amount; } public void transferTo(BankAccount b, double amount){ double bal = b.getBalance(); if (amount > this.balance) System.out.println("Insufficient funds. Can't transfer"); else { this.balance = this.balance - amount; b.setBalance(bal + amount); } } public String toString(){ String str; str = "Name: " + name + "\tBalance: " + balance; return str; } public static void main(String[] args){ BankAccount.setInterestRate(0.01); BankAccount A, B, C, D, E; A = new BankAccount("Art", 100.00); B = new BankAccount("Bob", 200.00); C = new BankAccount("Chuck", 300.00); D = new BankAccount("Dirk", 400.00); E = new BankAccount("Emily", 500.00); A.deposit(50.00); B.withdraw(25.00); C.addInterest(); D.transferTo(C, 50.00); System.out.println("Number of accounts: " + BankAccount.getNumAccounts()); System.out.println(A + "\n" + B + "\n" + C + "\n" + D + "\n" + E + "\n"); } } Inheritance: Concept Suppose that we are developing a database program for record-keeping at a university and we need to design the following classes. Employee Faculty Person Student Staff Undergrad Grad CSCI 2110: Module 1 Srini Sampalli 27 You will notice that many of the classes share common attributes. For example, all Undergrads share some common attributes with the Student class in addition to having their own attributes. This means that we can arrange the classes in a class hierarchy. Person Student Employee Undergrad Grad Faculty Staff CSCI 2110: Module 1 Srini Sampalli 28 There are many examples in which class hierarchies can be developed. Vehicle Car Truck Sportscar Minivan Animal Vertebrate Invertebrate Fish Amphibian Reptile Bird Mammal Notice that the class hierarchy can be extended as required. CSCI 2110: Module 1 Srini Sampalli 29 When you have a class hierarchy where common attributes are shared, inheritance can be used in programming. CSCI 2110: Module 1 Srini Sampalli 30 What is inheritance (in object-oriented programming) ? With a class hierarchy, we can start the design of a class at a higher level (e.g., Person) and extend it to the class at the lower level (e.g., Student). The Student class is said to inherit the properties of the Person class. It will have the behaviour of the Person class plus its own specialized behaviour. The process of deriving a new class based on an existing class is called Inheritance. Person Student Employee Undergrad Grad Faculty Staff CSCI 2110: Module 1 Srini Sampalli 31 How do we program inheritance? We extend an existing class into a new class. Notice the keyword “extends” in the class declaration. Person.java public class Person { Person … } public class Student extends Person Student.java { Student … } CSCI 2110: Module 1 Srini Sampalli 32 Superclass , Subclass and the UML Notation for Inheritance Person Superclass -the generalized class Notice the UML aka the base class notation Student Subclass -the specialized class aka the derived class CSCI 2110: Module 1 Srini Sampalli 33 Why use inheritance? The subclass will inherit the properties of the superclass. Νο need to repeat the instance variables of the super class (Person) in the sub class (Student). All the methods of the parent class can be used by the sub class object. Advantages: Code modularization. Code reusability. Accessibility of methods by other classes. Code extension by creating class hierarchies. CSCI 2110: Module 1 Srini Sampalli 34 How can you decide if two classes have an inheritance relationship? Answer: If there is an “is-a” relationship between the classes, then it is inheritance. Car is a Vehicle à Inheritance Rectangle is a Shape à Inheritance Monkey is an Animal à Inheritance Student is a Person à Inheritance CSCI 2110: Module 1 Srini Sampalli 35 An example program: Undergrad extends Student, Student extends Person Person ----------------------------------------------- fName: String lName: String Person class has attributes ----------------------------------------------- first name and last name Constructor, getters, setters, toString Student ----------------------------------------------- Student class has attribute ID only. ID: String It inherits first name and last name. ----------------------------------------------- Constructor, getter, setter, toString Methods in the superclass can also be used on the Student object. Undergrad Undergrad class has attribute major. ----------------------------------------------- It inherits first name, last name major: String ----------------------------------------------- and ID, and methods Constructor, getter, setter, toString from its super classes. CSCI 2110: Module 1 Srini Sampalli 36 Person class //class Person public class Person{ private String fName; private String lName; public Person(String fName, String lName){ this.fName=fName; this.lName=lName; } public String getfName(){return fName;} public String getlName(){return lName;} public void setfName(String fName) {this.fName=fName;} public void setlName(String lName) {this.lName=lName;} public String toString(){return "Name: " + fName + " " + lName;} } CSCI 2110: Module 1 Srini Sampalli 37 Student class public class Student extends Person{ private String ID; public Student(String fName, String lName, String ID) { super(fName, lName); this.ID = ID; } Calls the super class constructor public String getID(){return ID;} public void setID(String ID){this.ID=ID;} public String toString(){ return super.toString() + "\nID: " + ID;} } Calls the super class toString method CSCI 2110: Module 1 Srini Sampalli 38 Undergrad class //class Undergrad public class Undergrad extends Student{ private String major; public Undergrad(String fName, String lName, String ID, String major) { super(fName, lName, ID); this.major = major; } public String getMajor(){return major;} public void setID(String major){this.major=major;} public String toString(){ return super.toString() + "\nMajor: " + major;} } CSCI 2110: Module 1 Srini Sampalli 39 Undergrad Demo //Client program that creates and uses an Undergrad student object import java.util.Scanner; public class UndergradDemo{ public static void main(String[] args){ Scanner kbd = new Scanner(System.in); System.out.println("Enter first name: "); String f = kbd.nextLine(); System.out.println("Enter last name: "); String l = kbd.nextLine(); System.out.println("Enter ID: "); String i = kbd.nextLine(); System.out.println("Enter major: "); String m = kbd.nextLine(); Undergrad s1 = new Undergrad(f, l, i, m); System.out.println("\n\n" + s1 + "\n"); } } CSCI 2110: Module 1 Srini Sampalli 40 Method Overriding Question: Can a method in the subclass have the same name and same signature as a method in the superclass? Answer: Yes! The method in the subclass is said to override the method in the superclass. CSCI 2110: Module 1 Srini Sampalli 41 Abstract Class An abstract class in Java is one from which objects cannot be instantiated. It just defines the variables and the methods. Methods can also be abstract. An abstract method just has a header – no body. Sub-classes must implement the abstract methods. public abstract class Animal{ public class Lion extends Animal{ private String type; private String subtype; public Animal(String t){type = t;} public Lion(String t, String s){ public void display(){System.out.println("I am an animal");} super(t); public abstract void makeSound(); subtype = s; } } public void makeSound(){ System.out.println("Roar"); } } public class LionDemo{ public static void main(String[] args){ Lion l = new Lion("Mammal", "Wild"); l.display(); l.makeSound(); Output: } I am an animal } Roar CSCI 2110: Module 1 Srini Sampalli 42 Interface An interface is just a collection of method declarations with no data and no bodies. That is, the methods are just method signatures. Any class that “implements” an interface guarantees to implement all of the methods. Thus an interface enforces an API in software design. public interface Sellable{ public class Book implements Sellable{ public double listPrice(); //price of the object private String title; public double lowestPrice(); //lowest acceptable price private double price; } public Book(String t, String p){ title = t; price = p; } public double listPrice(){ return price*1.5; } public double lowestPrice(){ return price/2; } } CSCI 2110: Module 1 Srini Sampalli 43 The Object Class § In Java, every class inherits implicitly from a class called Object. § Thus, any class that extends a class A also extends the class Object by transitivity. public class Rectangle {…} implicitly means public class Rectangle extends Object {...} § The Object class library provides two sets of methods: § Utility methods (e.g., equals, toString, clone) § Methods for multi-threading CSCI 2110: Module 1 Srini Sampalli 44 The entire Java standard library is just a hierarchy of classes. The superclass for all classes is the Object class. CSCI 2110: Module 1 Srini Sampalli 45 POLYMORPHISM Polymorphic: Many forms CSCI 2110: Module 1 Srini Sampalli 46 Polymorphism in Java § The third pillar of object-oriented programming. § What is polymorphism? Polymorphic à many forms. § In OOP, it means the ability of one object to be treated, or used, like another. § It works for objects in the inheritance hierarchy. § In other words, we can use a reference of a superclass type to refer to an object of its subclass type. CSCI 2110: Module 1 Srini Sampalli 47 A simple example to illustrate Polymorphism Suppose we have: public class A{ //code … } A public class B extends A { //code …} public class C extends B {//code …} B C CSCI 2110: Module 1 Srini Sampalli 48 A simple example to illustrate Polymorphism Suppose we have: public class A{ //code … } A public class B extends A { //code …} public class C extends B {//code …} B Then in the client program(main): A obj; //obj is an object of type A obj = new A(); à OK C CSCI 2110: Module 1 Srini Sampalli 49 A simple example to illustrate Polymorphism Suppose we have: public class A{ //code … } A public class B extends A { //code …} public class C extends B {//code …} B Then in the client program(main): A obj; //obj is an object of type A obj = new A(); à OK C obj = new B(); à also OK! obj = new C(); à also OK! CSCI 2110: Module 1 Srini Sampalli 50 A simple example to illustrate Polymorphism Suppose we have: public class A{ //code … } A public class B extends A { //code …} public class C extends B {//code …} B Then in the client program(main): A obj; //obj is an object of type A obj = new A(); à OK C obj = new B(); à also OK! obj = new C(); à also OK! Polymorphism allows you to declare an object of a superclass type and instantiate an object of a subclass using the same reference. CSCI 2110: Module 1 Srini Sampalli 51 Another example: GameEntity Building the Star Wars game In a client program, we can declare: Actor Weapon GameEntity obj1, obj2, obj3, obj4; and then use obj1, obj2, etc. to create any type of object: Jedi Clone Sword LightSaber obj1 = new GameEntity(); obj2 = new Weapon(); obj3 = new Jedi(); obj4 = new LightSaber(); For instance, we can declare an array of GameEntity objects and then assign them to different types of objects within the program at runtime. GameEntity[] obj = new GameEntity; CSCI 2110: Module 1 Srini Sampalli 52 Polymorphism doesn’t work in GameEntity reverse For example, suppose we have: Actor Weapon Weapon obj5; then we cannot create: Jedi Clone Sword LightSaber obj5 = new GameEntity(); Similarly: Also: Sword obj6; Clone obj7, obj8; obj6 = new Weapon(); obj7 = new Weapon(); obj8 = new Sword(); CSCI 2110: Module 1 Srini Sampalli 53 The instanceof operator § In a large program, it becomes necessary to keep track of (and test) what type of object is referred to by the variable. § A useful operator to do this is called instanceof § X instanceof Y returns true if X refers to an object of type Y or a subclass (any number of levels down) of Y. CSCI 2110: Module 1 Srini Sampalli 54 Example to illustrate instanceof operator GameEntity obj2 For example, suppose we have: Actor Weapon GameEntity obj1, obj2, obj3; obj1 = new Jedi(); obj1 obj3 obj2 = new Actor(); Jedi Clone Sword LightSaber obj3 = new Sword(); Then: System.out.println(obj1 instanceof Jedi); à will display true System.out.println(obj2 instanceof Actor); à True System.out.println(obj3 instanceof Sword); à True System.out.println(obj2 instanceof GameEntity); à True System.out.println(obj2 instanceof Clone); à False System.out.println(obj3 instanceof LightSaber); à False System.out.println(obj3 instanceof Weapon); à True CSCI 2110: Module 1 Srini Sampalli 55 Casting § Polymorphism works downwards in a class hierarchy (superclass to subclass). § Can we do the reverse (i.e., can we use the reference of a subclass type to refer to an object of a superclass type)? § Yes – by casting (similar to casting a double as an int) CSCI 2110: Module 1 Srini Sampalli 56 Example to illustrate casting in Polymorphism GameEntity For example, suppose we have: Actor Weapon Jedi j1, j2; GameEntity g1; Jedi Clone Sword LightSaber Then: j1 = new Jedi(); //OK g1 = j1; //OK g1 = new GameEntity(); //OK j2 = g1; //not OK j2 = (Jedi) g1; // OK – g1 has been cast to Jedi. CSCI 2110: Module 1 Srini Sampalli 57 Generics in Java CSCI 2110: Module 1 Srini Sampalli 58 A simple example to illustrate the concept and power of generics… Suppose you write a class that has a bunch of methods for a Rectangle object: public class SomeClass{ private double num; private char ch; private Rectangle rect; //Bunch of methods that operate on the Rectangle object //method to add a rectangle object //method to remove a rectangle object //method to retrieve a rectangle object //method to change a rectangle object ….etc, etc. } CSCI 2110: Module 1 Srini Sampalli 59 After you develop the class, you are told that you need a similar class to handle Circle objects, Triangle objects, Quadrilateral objects, etc…. CSCI 2110: Module 1 Srini Sampalli 60 A silly way to write the class would be… public class SomeClass{ private double num; private char ch; private Rectangle rect; private Circle circ; private Triangle tri; private Quadrilateral quad; //bunch of methods for rectangle objects //bunch of methods for circle objects //bunch of methods for triangle objects //bunch of methods for Quadrilateral objects ….etc, etc. } CSCI 2110: Module 1 Srini Sampalli 61 With Generics, you can write a class with just one set of methods that can be applied to any kind of object. CSCI 2110: Module 1 Srini Sampalli 62 Here’s the same class written using Generics …. public class MyCollection{ private double num; private char ch; private T item; //method to add an item of type T public void add(T item, …) //method to remove an item of type T public void remove(…) //method to retrieve an item of type T public T get(…) ….etc, etc. CSCI 2110: Module 1 Srini Sampalli 63 } From a client program, you can create and manipulate different types of objects using the same class…. public class Demo{ public static void main(String[] args){ MyCollection r1 = new MyCollection(); MyCollection c1 = new MyCollection(); MyCollection t1 = new MyCollection(); ….etc, etc. } CSCI 2110: Module 1 Srini Sampalli 64 Generics Program Example: Create a Grade class that has one instance variable called value, constructor to set the value, get and set methods and a toString method. The Grade class must be generic such that it must work for either a String object or a Integer object. //generic class Grade public class Grade{ private T value; public Grade(T entry){value = entry;} public void setValue(T entry){value = entry;} public T getValue(){return value;} public String toString(){return “” + value;} } //demo client class public class GradeDemo{ public static void main(String[] args){ Grade m1 = new Grade(“A”); Grade m2 = new Grade(“86”); System.out.println(m1); System.out.println(m2); m1.setValue(“A+”); m2.setValue(91); System.out.println(m1); System.out.println(m2); } } CSCI 2110: Module 1 Srini Sampalli 65

Use Quizgecko on...
Browser
Browser