CMSC132 Quiz 1

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Interface Example: CanFlyExample public interface CanFly { public void takeOff(); public void fly(); public static final int MAX_FLIGHT_SPEED = 200; public static void displayInfoAboutHelicopters() { System.out.println("Helicopters are cool."); } public default void land() { System.out.println("Object falls to the ground."); } } Explain characteristics about this interface

"public interface CanFly { public void takeOff(); public void fly(); public static final int MAX_FLIGHT_SPEED = 200; public static void displayInfoAboutHelicopters() { System.out.println("Helicopters are cool."); } public default void land() { // inheritance with interfaces System.out.println("Object falls to the ground."); } /* land() method is already implemented in every class that implements CanFly interface. Can override if we want. all other methods must be implemented in any class that implements CanFyl interface */ } interface = skeleton - knows how to takeoff, fly, and land This is a polymorphic variable an owl, helicopter, etc all can fly. For example, because owls and helicopters land differently, you can write code to behave differently. Dynamic Dispatch: will run code for a specific thing that can fly (determined at runtime) "process of selecting which implementation of a polymorphic operation (method or function) to call at run time" CanFly x = new CanFly(); // does NOT work CanFly x = new Plane(); // Plane = class that implements CanFly interface x can access anything in interface but NOT in class that implements interface

SQ1: What is a "static" member?

"those which belongs to the class and you can access these members without instantiating the class"

Implements vs. Extends Explain... class X extends Y implements A, B, C {...}

- X = subclass of Y, Y = superclass of X - A, B, C = interfaces - X can only directly extend 1 thing! Can implement as many things as you want - X inherits all features of Y - X must implements all non-default instance methods in A, B, C - X "is a" Y (Liskov Substitution Principle) - X "can do" A, B, C - An instance of X can be assigned to variables of types X, Y, A, B, C - An instance of X satisfies types X, Y, A, B, C - An instance of X is only "class X"

Enumerated Types (enums) What is an "enum"? Write an example of an enum for the days of the week: Loop through all the days in the enum enumExampleSimple: enumExampleComplex:

- an "enum" is a lot like a class - there are a small # of pre-defined instances, identified with symbolic constants enumExampleSimple: public enum Day { SUN, MON, TUE, WED, THU, FRI, SAT; } /* IMPORTANT: Loop through all the days */ for (Day currentDay : Day.values()) { // Implicitly calling toString! System.out.println(currentDay + ": " + getWorkHours(currentDay)); } // NEED .values() method!! - the way to loop through the enum

Comparing enums + classes

- both have instance members (variables + methods) - both have static members (variables + methods) diff: constructors are private for enum - instances of the enum are the symbolic constants that are declared internally

Object class: What is it? - relationship with inheritance? - What methods does Object class contain?

- if your class doesn't explicitly extend something, it will extend Object - object is always at the root of an inheritance tree - toString() and equals() methods are in the Object class these are normally overriden bc equals() is ==

Example: Dynamic Dispatch, Late Binding Person[] list = new Person[3]; list[0] = new Person("Fred", 123); list[1] = new Student("Susan", 456); list[2] = new Faculty("Fred", 789); for(Person p : list) { p.walk(); } What will happen?

0 = walk like Person 1 = walk like Student 2 = walk like Faculty -- this is all because of late binding

Overloading vs. Overriding Overloading: methods in a class w/ the same name but different parameter type Overriding: subclass "replaces" inherited methods from super class Has matching prototype but different implementations Return type can be "more specific" Visibility may be increased but not decreased Is this a proper override? public class Person { private Person getParent(); } public class Student extends Person { @Override (1) public Student getParent() {...} public student getParent(int n) {...} (2) }

1) override 2) overload

SQ1: What is an "instance" member?

A member declared within a class

API + Encapsulation: StudentRosterExample What do we mean by API? What's encapsulation? - Data encapsulation + Procedural encapsulation

API = external features of class (public members) - as long as you haven't changed the API, you don't have to change any other code Data encapsulation = public vs. private members Procedural = the API doesn't specifically state HOW something is done - procedure = algorithm, isn't specified so it can be changed later "encapsulate what might change"

SimpleIteratorExample: Explain what's happening public class SimpleIteratorExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("blue"); list.add("yellow"); list.add("black"); list.add("orange"); list.add("purple"); /* ArrayList implements Iterable, so... */ Iterator<String> iterator = list.iterator(); while(iterator.hasNext()) { String s = iterator.next(); System.out.println(s); } } }

An ArrayList list of type String is created and various colors are added to it. Then the ArrayList implements Iterable, so an Iterator called iterator is also created using the hasNext() method, it checks to see if there's a next element while there is, another element in the list, it shifts to the next element and then it gets printed out

Wrapper Classes: What is Boolean (example)? Instantiating Wrapper Objects vs. Auto-Boxing/Unboxing - Show how to do this.

Boolean is a shell around the primitive boolean - always collects objects for Collections (for Collections of numbers --> use wrapper) Wrappers = immutable Integer x = Integer.valueOf(7); ^^ referencing to a 7 that already exists (no need for multiple 7s) "In Java, wrapper classes are immutable, each wrapper class stores a list of commonly used instances of its own type in form of cache" - creating Objects is expensive (use new keyword which allocates memory in heap) - need to use .valueOf() to cache Auto-Boxing/Unboxing: Integer x = 7; // auto-boxing Sysout(x + 2); // auto-unboxing, x is an Object - unwraps from Object to primitive Integer z = x + 2; - gets unwrapped, gives primitive 7, then autoboxes z - z + x are references to Objects

Summary: page 11 of notes Can classes, interfaces, and enums have these? 1) instance variable 2) static variable 3) instance method implementations 4) static method implementations 5) instance method prototype (no code) 6) constructors 7) number of instances? instance = object

Class: 1) Yes 2) Yes 3) Yes 4) Yes 5) Yes, must be declared as abstract 6) Yes 7) unlimited Interface: 1) No 2) Yes, must be final 3) Yes, if declared as "default" 4) Yes 5) Yes 6) No 7) none Enum: 1) Yes 2) Yes 3) Yes 4) Yes 5) No 6) Yes, it must be private 7) Fixed #

Privacy Leaks: MarylandLicensePlate (look on Eclipse) - Spot the problems in each of the Driver classes Driver01: public class Driver01 { public static void main(String[] args) { MarylandLicensePlate plate = new MarylandLicensePlate(); System.out.println(plate); plate.symbols = "THIS IS FAWZI'S AWESOME CAR".toCharArray(); System.out.println(plate); } } Driver02: public class Driver02 { public static void main(String[] args) { MarylandLicensePlate plate = new MarylandLicensePlate(); char[] localCopy = plate.getSymbols(); for (int i = 0; i < localCopy.length; i++) { localCopy[i] = '@'; } System.out.println(plate); } } Driver03: public class Driver03 { public static void main(String[] args) { char[] symbols = "5XY1257".toCharArray(); MarylandLicensePlate plate = new MarylandLicensePlate(symbols); System.out.println(plate); for (int i = 0; i < 7; i++) { symbols[i] = '@'; } System.out.println

Driver01: - public instance variables (can change contents of license plate) Driver02: - getter - aliased, can change contents return symbols vs. return Arrays.copyOf(symbols, 7); - a local copy can change contents of array Driver03: - have reference to array, able to change license plate contents - right after constructor ran (are aliased) - need to make a copy this.symbols = Arrays.copyOf(symbols, 7);

Assume walk() is overriden by subclasses Person: (1) walk() Student: (2) walk() Faculty: (2) walk() Person p = new Student(); p.walk(); // Which will run? Early (static) binding vs. Late (dynamic) binding

Early (static) binding - faster (small difference) - will run Person version - compiler makes decision (What is type of variable?) Late (dynamic) binding - dynamic dispatch - runs Student version - decision made at runtime (What is class of object?)

this vs. super this - reference to current object (constructors / instance methods) super - used in constructors / method calls Explain super using Person example How is instance of subclass constructed? - Ex: Student class illustrates super Write a constructor for Student with String name, int idNum, doubleGPA, and int admissionYear as parameters Also, write a no argument constructor - What if you don't add super() Write a copy constructor Write a constructor that invokes another constructor (String name, int idNum, double GPA as parameters) Write a toString() method using super Write an equals() method using super

If you're writing a constructor for Undergrad class, it will call super on Student (Student calls super on Person) - creates a chain call to superclass constructor. Why? - members are private in super class, so it won't be visible in subclasses) - super class likely has "policies" that need to be enforced Ex: Student class illustrates super - can't access private features from the super class in the subclass (can't access name + id# directly) public Student(String name, int ID, double GPA, int admissionYear) { super(name, ID); this.GPA = GPA; this.admissionYear = admissionYear; } public Student() { super(); // What if we leave this out? GPA = 0.0; admissionYear = 0; } - if super() is taken out, by default, Java will include a super() constructor with no arguments -- similar to default constructor public Student(Student other) { super(other); // other is Student, not Person.... OK? GPA = other.GPA; admissionYear = other.admissionYear; } - can assign a Student variable to a Person! It's ok! public Student(String name, int ID, double GPA) { this(name, ID, GPA, 2021); } - invokes another constructor in Student class (other constructor uses super, so it's not needed here) @Override public String toString() { return super.toString() + "GPA: " + GPA + "admitted: " + admitYear; } @Override public boolean equals(Object other) { if (this == other) { return true; } if ( ! (other instanceof Student)) { return false; } Student s = (Student)other; return super.equals(s) && GPA == s.GPA && admitYear == s.admitYear; } // even though we inherit a lot of stuff from the super class, you need to use super when methods are overriden / you want to access private instance variables in super class

enumExampleComplex: Explain what is happening public enum Day { SUN("Sunday", 0), MON("Monday", 8), TUE("Tuesday", 6), WED("Wednesday", 8), THU("Thursday", 6), FRI("Friday", 8), SAT("Saturday", 0); private String name; private int workHours; // Note: Constructors must be private! private Day(String name, int workHours) { this.name = name; this.workHours = workHours; } public String getName() { return name; } public int getWorkHours() { return workHours; } } public class WorkHours { public static void main(String[] args) { for (Day d : Day.values()) { System.out.println(d.getName() + ": " + d.getWorkHours()); } } }

In the enum, each day has greater characteristics than in the Simple example. - It writes out the day completely and how many hours of work are done that day NOTE: CONSTRUCTORS MUST BE PRIVATE!

Iterator + Iterable Interfaces: When can you call an iterator? Write out structure for the ITERABLE interface. - Assume coll is an Iterable collection of Cats - We can ask the collection to give us an Iterator to go through its elements Write out structure for the ITERATOR interface. - What is the purpose of an iterator? - Why are Iterators limited?

Iterator (thing): an object that can sequentially access the elements of a collection 1 time Iterable (adjective): a collection that implements the Iterable interface has the ability to provide you with an "Iterator" to go through its own elements If you have a collection that supports the Iterable interface, you can call an iterator interface Iterable <T> { // T = parametrized type Iterator <T> iterator(); ... } Iterator <Cat> iterator = coll.iterator(); Iterable = about Collections (characteristics) interface Iterator<E> { boolean hasNext(); // sees if there's a next element E next(); // goes to next element word remove(); // removes thing } "The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container." - Iterator = limited because it is a one-time use thing... will only go through the list 1 time * for-each loops are really just iterators *

This follows Person example: Valid? Person p = new Person(); Student s = new Student(); Person x = s;

Person p = new Person(); Student s = new Student(); Person x = s; - even though s is a Student, it has all the characteristics of Person so it's ok. - If it was Student y = p; this wouldn't work

Person example: Person: (1) String name int idNum String getName() String toString() boolean equals(Object) Student: (2) double gpa int admissionYear CanStudy: (interface connected to Student) Faculty: (2) Undergrad: (3 under Student) Grad: (3 under Student) ---------------------------------------------- Are these valid? Person x = new Student(); Student y = new Person();

Person x = new Student(); √ Student y = new Person(); X - a Student is always a Person but a Person isn't always a Student (ex. Person could be a Faculty) A Student is a Person with some extra stuff attached

Privacy Leaks - Why do you want to encapsulate members?

Suppose a mutable member has been intentionally encapsulated... - don't want users to change your internal code w/o going through you API - you want to have control over how/what gets changed - exposing private member data is typically a privacy leak Modification of its "state" within the class is expected ("mutation") Rule of Thumb: direct mutation by external code shouldn't be possible

Casting: Synthax Foo x = (Bar) x; // see this in equals method - expression that could be treated as type Bar Idea: even though variable X is not type Foo, we want to treat the object as type Foo When will it compile? When will it run successfully? Upcasting (up the tree) Student s = ...; Person p = (Person) s; Person p = s; Downcasting (down the tree) Person p = ...; Student s = (Student) p; p = new Faculty(); p = new Undergrad();

Synthax Foo x = (Bar) x; // see this in equals method - expression that could be treated as type Bar Idea: even though variable X is not type Foo, we want to treat the object as type Foo When will it compile? When Bar is either above or below Foo on the inheritance tree When will it run successfully? When the object is type Bar (otherwise, throws a ClassCastException) Upcasting (up the tree) Student s = ...; Person p = (Person) s; // all Students are Person so it's ok (explicitly done) Person p = s; // implicit casting, equivalent to line above Downcasting (down the tree) Person p = ...; Student s = (Student) p; // will compile, hopes that we did it right /it will work @runtime - will throw a ClassCastException p = new Faculty(); // Faculty isn't a Student, it's fine p = new Undergrad(); // Undergrad is a Student, will work If p refers to an object of type Student, it's fine if p refers to an object not of type Student, throws ClassCastException Equals metohd - instanceof checks the type

SQ1: True/False: a. A class can implement numerous interfaces. b. Interfaces are useful for inheritance. c. Interfaces are useful for polymorphism. d. A class implementing an interface must implement... i. The public methods in the interface. ii. Methods in the interface that are not implemented in other classes iii. All methods in the interface. e. You cannot instantiate an interface directly. f. An interface can be used as a type for a variable. g. An interface can be used as the type for a "polymorphic collection".

a. True b. False c. True d. iii e. False f. True g. True

Back to Person example every object has 1 class, it can't be changed object my satisfy many types Person p = new GradStudent(); 1) What is the type of the variable? 2) What is the class of the object? 3) What are the type(s) of the object?

all GradStudents are people 1) Person 2) GradeStudent w/ all inherited methods in super class 3) This object is type GradStudent, Student, Person, Object, CanStudy - p satisfies all these types, even CanStudy interface

Collections Class: CollectionsExample What is it? What do each of these methods do? public class CollectionsExample { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 10; i < 100; i += 10) { list.add(i); } list.add(57); System.out.println("Original list: " + list); *Collections.shuffle(list);* System.out.println("Shuffled list: " + list); *int max = Collections.max(list);* *int min = Collections.min(list);* System.out.println("Max is " + max + ", min is " + min); *Collections.sort(list);* System.out.println("After sorting: " + list); *int index = Collections.binarySearch(list, 57);* System.out.println("57 is located at index " + index); *Collections.reverse(list);* System.out.println("After reversing: " + list); } }

contains static methods that work on all different Java collections shuffle() - randomizes order of collections (fast) max() - finds largest value (largest number in this case, uses compareTo for Objects) min() - finds the smallest value sort() - based on compareTo binarySearch() - O(logn), must sort it before reverse() - reverses elements in list

enumExampleSimple: Explain what is happening public enum Day { SUN, MON, TUE, WED, THU, FRI, SAT } public class WorkHours { public static int getWorkHours(Day day) { if (day == Day.MON || day == Day.WED || day == Day.FRI) { return 8; } else if (day == Day.TUE || day == Day.THU) { return 6; } else { return 0; } } public static void main(String[] args) { /* IMPORTANT: Loop through all the days */ for (Day currentDay : Day.values()) { // Implicitly calling toString! System.out.println(currentDay + ": " + getWorkHours(currentDay)); } if (Day.WED.compareTo(Day.SUN) < 0) { System.out.println("Wednesday comes before Sunday"); } else { System.out.println("Wednesday comes after Sunday"); } System.out.println("Tuesday's index is: " + Day.TUE.ordinal()); System.out.println("The 4th day is: " + Day.values()[3]); } }

getWorkHours(Day day) - returns the number of work hours there are specific to the day passed through the parameter in main method: - for-each loops traverses through the entire enum and prints out the day and it's corresponding number of work hours Day = name of enum Day.WED.compareTo(Day.SUN) < 0 - which comes first in the list (will return the else statement bc SUN is before WED in the enum) Day.TUE.ordinal(); - tells where the symbolic constant is located in the list (index) Day.values()[3]; - accessing index 3 in the list = WED

Mutability Define: - immutable class/object - mutable class/object - aliasing for immutable vs. mutable

immutable class/object: - state (instance variables) set during construction but can't be modified after that mutable class/object - state is set during construction and might be modified later aliasing = never a problem for immutable objects if mutable, you need to think about it more

Comparable interface - compareTo ComparableExample: Explain what's going on /* Note syntax here using generics... */ public class Dog implements Comparable<Dog> { private String name; private int size; public Dog(String name, int size){ this.name = name; this.size = size; } /* Should we use size or name? */ @Override public int compareTo(Dog other){ return name.compareTo(other.name); } public String toString() { return name + ":" + size + "lbs"; } }

interface Comparable <T> { public int compareTo(T other); } - defines the "natural order" for instances of the class ComparableExample: - comparing Dog with another Dog - compareTo() method... - natural order of Dogs is based on name (specifically for this example) other option for compareTo() method... @Override public int compareTo(Dog other){ return size - other.size; } // now natural order of Dogs is based on size need to decide how Dogs are being ordered (in this example, it's either name or size)

Memory Diagrams: MemoryExample - go through this example and draw a diagram to go along with it public class MemoryExample { private static int value; private static void f(int x, Dog dog) { value = 200; x = 17; dog.setName("Liz"); } public static void main(String[] args) { MemoryExample.value = 100; int x = 7; Dog dog = new Dog("Steve", 55); f(x, dog); // Will x change? Will the dog change? System.out.println("x is " + x); System.out.println("dog's name is " + dog.getName()); System.out.println("value is " + value); } }

note: static variables are stored in separate part of memory When f is done, it gets popped off the stack and it goes back into main method drawing: page 8 of notes

Equals method Assume that x + y are reference variables x == y (true when x + y are the same object - aliasing) x.equals(y) (true when x + y are objects that "look" the same - same state) equals() is used extensively throughout Collection Framework c.contains(a) - TRUE if there is an element in the Collection that is equal to a "Default" implementation of equals() method inherited from Object class - same as == Write an equals() method with type Dog

public boolean equals(Object other) { if(this == other) { return true; // checks if the current obj and parameter are the same. // If so, doesn't need to do other work (optimization) } if(!(other instanceof Dog)) { // is it a Dog? return false; } Dog dog = (Dog) other; return dog.name.equals(name) && dog.size == size; }

public class Base { public void m(int x) {...} // 1 } public class Derived extends Base { public int m(int x) {...} public void m(int x) {...} // 2 public void m(double x) {...} // 3 } For Derived class, will each method overload, override, or not compile? Valid? Base x = new Base(); Base y = new Derived(); Derived z = new Derived(); What method above (1, 2, 3) is called? x.m(5); y.m(6); y.m(7.0); z.m(8.0);

public class Derived extends Base { public int m(int x) {...} public void m(int x) {...} public void m(double x) {...} } - won't compile bc of return type, int is not a subtype of void (not related at all) - override - overload Base x = new Base(); √ Base y = new Derived(); √ Derived z = new Derived(); √ x.m(5); 1 (super class) y.m(6); 2 (late binding) - y = type Base, any Base class cna have parameter int, compiler will let it go through y.m(7.0); (won't compile) - doesn't know that Derived class exists - not all Persons are Students - Base class doesn't have a parameter of type double / this type of feature/behavior (compiler won't like it) z.m(8.0); 3

Inheritance (extending classes) - can look at UML (Unified Modeling Language) Diagram on page 13 of notes Animal: (1) int size Color color void eat() void sleep() Bird: (2) void fly() void eat() Dog: (2) String breed void bark() void chaseCar() Eagle: (3 under Bird class) Turkey: (3 under Bird class) void gobble() Bald Eagle: (4 under Eagle class) ----------------------------------------------- Explain public class Dog extends Animal {...} How many instance variables and how many things can Dog do? Is this valid in Dog class? Dog x = new Dog(); x.eat(); eat() method and Bird class Relationship between - Animal and Bird - Bird and Eagle Polymorphism: public void takeBath(Bird b) {...} 1) What kinds of objects can b represent? 2) What methods can be called on b?

public class Dog extends Animal {...} - Dog automatically has characteristics of Animal Dog: instance variables = 3 can do = 4 (4 methods total) Dog x = new Dog(); x.eat(); - this is valid if you're in Bird class and you want to use the old eat() method, can use super. If outside of Bird class, you can't use the old one Relationship between ... Animal and Bird - Animal = super class, Bird = subclass Bird and Eagle - Bird = super class, Eagle = subclass "is - a" relationship - transitivity - A bird is an animal √ - An animal is a Dog X Liskov Substitution Principle: "The principle defines that objects of a superclass shall be replaceable with objects of its subclasses without breaking the application. That requires the objects of your subclasses to behave in the same way as the objects of your superclass." Polymorphism: public void takeBath(Bird b) {...} 1) What kinds of objects can b represent? - Bird, Eagle, Bald Eagle 2) What methods can be called on b? - can call methods in Bird + Animal classes

For-each loops: ForEachExample What are the characteristics of for-each loops?

public class ForEachExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("blue"); list.add("yellow"); list.add("black"); list.add("orange"); list.add("purple"); for (String s : list) { System.out.println(s); } } } In for-each loop, type must match ArrayList type s = variable declaration list = name of collection - don't need an index variable - can't modify collection (add/remove using for-each loops) or else it will throw a ConcurrentModificationException

IteratorRemoveExample: Explain what's happening Want to remove values <50 public class IteratorRemoveExample { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 10; i < 100; i += 10) { list.add(i); } removeSmallValues1(list); removeSmallValues2(list); removeSmallValues3(list); } /* Three different versions of a method that is supposed to remove * all elements that are less than 50... */ private static void removeSmallValues1(ArrayList<Integer> list) { for (Integer value : list) { if (value < 50) { // auto-unboxing list.remove(value); } } System.out.println(list); } private static void removeSmallValues2(ArrayList<Integer> list) { for (int i = 0; i < list.size(); i++) { if (list.get(i) < 50) { // auto-unboxing list.remove(i); } } System.out.println(list); } private static void removeSmallValues3(ArrayList<Integer> list) { Itera

removeSmallValues1(list); - can't add/remove in a for-each loop - throws a ConcurrentModificationException removeSmallValues2(list); - will skip indices because the list keeps changing when a value <50 but the index number doesn't change (pitfall, logical error) - to fix... instead of list.remove(i) ... do list.remove(i--) removeSmallValues3(list); - this will work because it calls remove on Iterator - note that if methods calls remove on ArrayList, it will throw a ConcurrentModificationException - use Iterators when removing from Collections

ArrayList Generic Notation: - create an ArrayList, x, of Cats Deprecated Notation: Why is this not favorable?

wrapper around array Generic Notation: ArrayList<Cat> x = new ArrayList<>(); - won't compile if another Object type is put into the ArrayList Deprecated: ArrayList x = new ArrayList(); // list of Cats - if you accidentally put a Dog in a list of Cats, it will compile - when Dog gets removed from list, it will cause problems


Set pelajaran terkait

Drivers ed (quizzes and crossword)

View Set

MKTG320 Chapter 9, Chapter 12, Chapter 11, Chapter 16, Chapter 14, Chapter 10

View Set

Chapter 31 EMT Orthopedic Injuries Q&A II

View Set

Unit 10 Study Guide - 𝕗𝕦𝕔𝕜 𝕓𝕚𝕥𝕔𝕙𝕖𝕤 𝕘𝕖𝕥 𝕞𝕠𝕟𝕖𝕪

View Set

Waves and Electromagnetic Spectrum

View Set

Chapter 10, 11, 12 Multiple Choice.

View Set

Chapter 11: Race & Ethnicity Quiz & Terms

View Set