Java
node E (A preorder traversal is a traversal that first visits the root, then recursively visits the left child, then recursively visits the right child. The first node printed is the root. Then all nodes of the left subtree are printed (in preorder) before any node of the right subtree.)
(preorder traversal) What node is visted after node C?
D. Student s = new Person(); (EXPLANATION A SUPERCLASS reference VARIABLE can hold an OBJECT of that SUPERCLASS or of any of its superclasses. However We're unable to to declare a VARIABLE of the SUBCLASS and put in a SUPERCLASS OBJECT. For example a "Shape" REFERENCE VARIABLE can hold a "Rectangle" or "Square" OBJECT but a Square reference cannot hold a Shape OBJECT because not all SHAPES are squares)
A class Student inherits from the superclass Person. Which of the following assignment statements will give a compiler error? A. Person p = new Person(); B. Person p = new Student(); C. Student s = new Student(); D. Student s = new Person();
C. A has-a relationship. The Book class has an Author attribute. (EXPLANATION: A Book has an Author associated with it. Note that you could also say that an Author has many Books associated with it.)
An online site shows information about Books and Authors. What kind of relationship do these two classes have? A. An is-a relationship. The Author class should be a subclass of the Book class. B. An is-a relationship. The Book class should be a subclass of the Author class. C. A has-a relationship. The Book class has an Author attribute.
•The super keyword is a direct reference to the parent class and its fields, methods, and constructors •Can call parent constructors using super: super() Can also call overloaded constructors: super(param1, param2, ...) •Useful when needing to initialize attributes declared in a parent and there is a constructor available
Calling a Parent Constructor
Breadth-first search Breadth First Search uses logic similar to that of a depth-first search to explore topics, but stores future states with a queue. At each step, the search explores the option that has been waiting the longest, effectively branching out over different directions before going deeper. Says search at one level before going deeper
FITB: _______________ uses logic similar to that of a depth-first search to explore topics, but stores future states with a queue. At each step, the search explores the option that has been waiting the longest, effectively branching out over different directions before going deeper.
Depth First Search Depth-first search is an algorithm that continues exploring, deeper and deeper, along a single path until it hits a dead end. The algorithm then backs up to the last branching point and checks other options. It maintains a list of future states to explore using a stack, always choosing the most recently inserted option to try next.
FITB: __________________________is an algorithm that continues exploring, deeper and deeper, along a single path until it hits a dead end. The algorithm then backs up to the last branching point and checks other options.
1. run-time
Fill In The Blank Polymorphism chooses which method definition to use at _______1_______
1. Creates CONSTANT VARIABLES 2. Prevents METHOD OVERRIDING 3. Prevents INHERITANCE
Fill In The Blank:
class Person { >>> private String name; } // How can we make the Student class inherit from class Person? public class Student extends Person { >>> private int id; public static void main(String[] args) { Student s = new Student(); System.out.println(s instanceof Student); System.out.println(s instanceof Person); } }
How can we make the Student class inherit from class Person?
•Use the keyword extends •The sub class will inherit all the available fields and methods in the base class •Need two classes: a base class and a sub class Other names: super/sub, parent(ancestor)/child(descendant)
How to Inherit
public void methodTwo(int i_) { }
Identify the METHOD OVERRIDING CONSTUCTOR
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the outer package separated by a dot (.). There is no practical limit on the depth of a package hierarchy, except that imposed by the file system. Finally, you specify either an explicit class name or a star (*), which indicates that
In a Java source file, import statements occur immediately following the package statement (if it exists) and before any class definitions. This is the general form of the import statement: import pkg1 [.pkg2].(classname | *);
Base
Inherit
•The protected modifier allows fields and methods to be accessed by sub classes •The private access modifier means the field/method cannot be accessed by sub classes, and public gives open access, so this somewhat of a middle ground
New modifier - protected
OVERRIDING Requires inheritance •Happens across parent and child classes Child changes parent definition •Everything (name, parameter list) must be the same OVERLOADING METHOD They all have the same NAME, DIFFERERENT ORDEr DIFFERENT NUMBER •Happens in the same class •Same name, but different parameter list
OVERRIDING VS OVERLOADING
•All classes in Java automatically inherit from Object •Gives a common ancestor, which means all classes inherit from Object This means all classes can also use Object as their data type for polymorphism Not great, since there are no field and very few methods •Three main methods we use: equals() hashCode() toString()
Object
1. INHERITANCE is used 2. The METHOD is defined in the base class and the current class extend that base class 3. The access modifier is private
Please select all the requirements needed for OVERRIDING a METHOD: 1. INHERITANCE is used 2. The METHOD is defined in the base class and the current class extend that base class 3. The access modifier is private 4. The PARAMETER LIST is different between the METHODS
0
Suppose T is a binary tree with 14 nodes. What is the minimum possible height of T?
False
TRUE FALSE: An Abstract class can be instantiated (i.e., we can make an object of an abstract class)
1. private modifier 2. protected modifier 3. public modifier 4. default
The _______1_______specifies that the member can only be accessed in its own class. The _______2_______specifies that the member can only be accessed within its own package and, in addition, by a subclass of its own class and another package. the _______3_______ specifies that the Classes can be seen everywhere. If the CLASS has no modifier or _______4_______the class is only visible by those and it's on package
True EXPLANATION: //The variables declared of the type Shape can hold OBJECTS of it's SUBCLASS Shape s1 = new Shape( ); Shape s2 = new Rectangle ( ); Shape s3 = new Square( ); A SUPERCLASS reference VARIABLE can hold an OBJECT of that SUPERCLASS or of any of its superclasses. FOR example, a "Shape" REFERENCE VARIABLE can hold a "Rectangle" or "Square" OBJECT. This is a type of POLYMORPHISM However We're unable to to declare a VARIABLE of the SUBCLASS and put in a SUPERCLASS OBJECT. For example a Square reference cannot hold a Shape OBJECT because not all SHAPES are squares Why is using a superclass reference for subclass objects allow us to write methods with parameters of type Shape or have arrays of type Shape and use them with any of its subclasses
True or False: A SUPERCLASS reference VARIABLE can hold an OBJECT of that SUPERCLASS or of any of its superclasses Shape s1 = new Shape( ); Shape s2 = new Rectangle ( ); Shape s3 = new Square( );
False
True or False: An ABSTRACT CLASS can be instantiated i.e. we can make an object of an abstract class
True
True or False: Most searches will add options in the order in which they are encountered
True EXPLANATION: If we have multiple sub classes that inherit from a super class we can form and inheritance hierarchy. Every sub class is a or is a kind of the SUPERCLASS.
True or False: One of the main reasons to use an inheritance hierarchy is that the instance variables and methods from a super class are inherited and can be used in a sub class without re-writing or copying code.
True
True or False: We must always override hashCode( ) if we override equals( )
False
True or false: We should always override equals ()
True
True or false: We should always override toString()
1. extends (EXPLANATION extends is Used to specify the parent class to inherit from. It is followed by the name of the parent class, like this: public class ChildName extends ParentName. If no extends keyword is used in the class declaration, then the class will automatically inherit from the Object class. To make a subclass inherit from a superclass, use the Java keyword extends with the superclass name when creating a new subclass as shown below.) EXAMPLE: public class Car extends Vehicle { }
We use the Java keyword _______1_______ to make one class inherit from another (test)
1. className.variable 2. className.method( ) All objects of a class have access to class instance variables and class methods, but these can also be accessed using className.variable or className.method().
What 2 lines of code can help objects of a class access in class instance variables and class methods?
remove(int)
What ARRAY LIST METHOD removes the items at its position and returns it
The toString( ) METHOD EXPLANATION: highly recommended to always consider overriding the toString( ) METHOD in our classes. The OBJECTS toString( ) METHOD returns a String representation of the OBJECT, which is very useful for debugging. The string representation for an OBJECT depends entirely on the object, which is why you need to override toString( ) METHOD In your classes We can use toString( ) METHOD Along with system.out.println()to display a text representation of an object, such as an instance of book: system.out.println(firstBook.toString()); This is useful for a properly overridden toString( ) METHOD. It would print out something like a SBN: 0201914670; the swing tutorial; a guide to constructing GUIs, second edition
What INHERITANCE METHOD is it important to override?
equals() •Used to compare objects Remember, we cannot use == for objects! •We need to override to compare the important fields of our classes See reading for more details, as there are some very important ones! •Don't always need to override See reading for details
What INHERITANCE METHOD is used to compare objects Remember, we cannot use == for objects! •We need to override to compare the important fields of our classes See reading for more details, as there are some very important ones! •Don't always need to override See reading for details
The hashCode( )Method (The Value return by hashCode( ) Is the objects hash code, which is an integer value generated by a hashing algorithm. By definition, if two objects are equal, there has code must also be equal. If you override the EQUALS( ) METHOD the hashCode( )Method has to be overridden as well.)
What INHERITANCE METHOD returns and objects hash code, and is overridden when the EQUALS( ) METHOD Is overridden as well
C. extends EXPLANATION: The extends keyword is used to specify the parent class. The keyword extends is used to establish an inheritance relationship between a subclass and a superclass. Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without repeating these in the code.
What Java keyword is used to set up an inheritance relationship between a subclass and a superclass? A. superclass B. parent C. extends D. class
&& (EXPLANATION: && can be used to combine tests) EXAMPLE: return (this.attribute1 == otherObj.attribute1) && this.attribute2.equals(otherObj.attribute2)
What OPERATOR may we use to check multiple attributes?
• •A way to organize related classes When working with packages, need to import
What are packages?
1. Reflexive: 2. Symmetric: 3. Transitive: 4. Consistent: The equals method implements an equivalence relation. It has these properties: • Reflexive: For any non-null reference value x, x.equals(x) must return true. • Symmetric: For any non-null reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true. • Transitive: For any non-null reference values x, y, z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true. • Consistent: For any non-null reference values x and y, multiple invocations of x.equals(y) must consistently return true or consistently return false, provided no information used in equals comparisons is modified. • For any non-null reference value x, x.equals(null) must return false. Bloch, Joshua . Effective Java (p. 38). Pearson Education. Kindle Edition.
What are the 4 equivalence relation the equals method implements?
1. Type @Override 2. Use the public boolean equals(Object other) method signature 3. Type cast other to your Classname 4. Return whether this object's attribute(s) equals the other object's attribute(s) with == for primitive types like int and double, or equals for reference types like String or another EXAMPLE: public boolean equals(Object other) { // Type cast other to your Classname Classname otherObj = (Classname) other; // Check if attributes are equal return (this.attribute == otherObj.attribute); // or this.attribute.equals(otherObj.attribute) if attribute a String
What are the 4 steps for using the EQUALS ( ) METHOD?
INHERITANCE HIERARCHY EXPLANATION: if we have multiple sub classes that inherit from a super class we can form and inheritance hierarchy. Every sub class is a or is a kind of the suPERCLASS. For example the image shows an inheritance hierarchy of shapes. The square is a rectangle and a sub class of rectangle. Rectangle is a shape and a sub class of sheep. In Java the class object is at the top of hierarchy. Every class in Java inherits from object and is an object. One of the main reasons to use an INHERITANCE HIERACHYis that the instance variables and methods from a superclass are inherited and can be used in a subclass without rewriting or copying code.
What can be formed if we have multiple SUBCLASSES that inherit from a SUPERCLASS?
the super keyword (EXPLANATION: the super Keyword used to call a method in a parent class. This is useful if a child class overrides an inherited method, but still wants to call it. If you are writing an equals method for a subclass, you can call the superclass equals using the super keyword to check the attributes in the superclass and then check the attributes in the subclass.) EXAMPLE: return super.equals(otherObj) && (this.attribute == otherObj.attribute)
What can be used to check the attributes in the SUPERCLASS and SUBCLASS SIMULTANULY
1. using the special keyword super() 2. passing appropriate parameters EXAMPLE: super( ); or super(theName) EXPLANATION: So, how do you initialize the superclass' private variables if you don't have direct access to them in the subclass? In Java, the superclass constructor can be called from the first line of a subclass constructor by using the special keyword super() and passing appropriate parameters, for example super(); or super(theName); as in the code below. The actual parameters given to super() are used to initialize the inherited instance variables, for example the name instance variable in the Person superclass. public class Employee extends Person { public Employee ( ) { // calls the Person() constructor super ( ) ; } public Employee(String theName) { // calls Person(theName) constructor super (theName); } }
What can call the SUPERCLASS CONSTRUCTOR of the PARENT in Java?
ACCESS LEVEL MODIFIERS ACCESS LEVEL MODIFIERS determine whether CLASSES can use a particular field or invoke a particular method. There are two levels of access control: At the top level- public or package private (no explicit modifier) at the member level- public, private, protected or packaged private (no explicit modifier)
What determines whether CLASSES can use a particular field or invoke a particular METHOD?
superclass EXPLANATION: A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a
What does a putting common attributes and behaviors of related classes into a single class hierarchy to develop?
Different levels of Control
What does this Access Level Graph show?
nodes (A binary tree is made up of a finite set of elements called nodes. This set either is empty or consists of a node called the root together with two binary trees, called the left and right subtrees, which are disjoint from each other and from the root. (Disjoint means that they have no nodes in common.) The roots of these subtrees are children of the root. There is an edge from a node to each of its children, and a node is said to be the parent of its children.)
What is a binary tree is made up of?
•Sometimes we want to say children classes should have a method they need to override, but don't want to give a base definition •Can make the method abstract No definition! •If a class has at least one abstract method, it must also be marked abstract •We cannot instantiate an object of an abstract class! •Useful for giving some common behavior when using inheritance
What is an abstract class
The CLASS OBJECT EXPLANATION In Java, the class Object is at the top of hierarchy. Every class in Java inherits from Object and is-an Object.
What is at the top of the hierarchy in Java?
•Parent method has a definition that works for it, but child needs a different definition Child has new attributes that will affect the method, but we still want the overall behavior Pet: cats and dogs walk, fish swim, all are movements •Can override a method by using the same name and parameter list as the parent, but provide new definition •Typically give the method an @Override annotation Used for the Java compiler and is a good reminder
What is method overriding?
The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.
What is polymorphism?
•Informal definition: storing a child object in a parent variable •A child object is still stored in memory! •This means that the method definition will be chosen by the data type in memory, not the data type of the variable When using an overridden method •However, the methods available are limited to what's in the parent class •Can be used to allow an ArrayList to hold different types Need to use inheritance and the ArrayList must hold a base type
What is polymorphism?
objref instanceof type EXPLANATION: , objref is a reference to an object and type is a class or interface type. If the object referred to by objref is of the specified type or can be cast to the specified type, then the instanceof operator evaluates to true. Otherwise, its result is false. (If objref is null, the result is also false.) Thus, instanceof is the means by which your program can determine if an object is an instance of a specified type at run time. instanceof evaluates to true if and only if an object is of a specified type or can be cast to that type. Beginning with Schildt, Herbert. Java: A Beginner's Guide, Ninth Edition (p. 581). McGraw Hill LLC. Kindle Edition.
What is the general form of the instanceof operator?
Objref instanceof type pattern-var (EXPLANATION: If instanceof succeeds, pattern-var will be created and contain a reference to the object that matches the pattern. If it fails, pattern-var is never created. This form of instanceof succeeds if the object referred to by objref can be cast to type and the static type of objref is not a subtype of type. The primary advantage of the pattern matching form of instanceof is that it reduces the amount of code that was typically needed by its traditional form. For example, consider this functionally equivalent version of the preceding example that uses the traditional approach)
What is the syntax for the pattern-matching form of the instanceof operator?
The Project Tab The Project Tab is one of the main tool windows. It contains t eh projects directory, SDK-specific external libraries and scratch files. Can opened by pressing Cmd 1
What is this
this Keyword Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. }
What keyword is used to refer any member of the current object from within an instance method or a constructor?
•Keyword this refers to the current object •Can be used to resolve ambiguity Which first name variable is the parameter? The class attribute? •Using this.firstName says use the class's attribute This means the plain firstName must be the parameter
What keyword is used to refer any member of the current object from within an instance method or a constructor?
What method is it considered highly recommended to override and is useful for displaying a text representation of an object?
What makes overriding the toString( ) METHOD highly recommended
ARRAYS and ARRAYLISTS can use the SUPERCLASS type to hold SUBCLASS OBJECTS ----------------------------------------------------------------------------- // This shape ARRAY can hold the subclass objects too Shape[] shapeArray = { new Rectangle(), new Square(), new Shape() }; // The shape ARRAYLISTcan add subclass objects too ArrayList<Shape> shapeList = new ArrayList<Shape>(); shapeList.add(new Shape()); shapeList.add(new Rectangle()); shapeList.add(new Square()); Notice that the add method in ArrayLists actually has a parameter type of Object, add(Object), but we can use it with any subclass object!
What makes the INHERITANCE HIERARCHY useful when working with ARRAYS and ARRAY LISTS
Instanceof operator (EXPLANATION: Instanceof operator. Returns a Boolean if the Object parameter (which can be an expression) is an instance of a class type.Input 1: An object or Expression returning an object.Input 2: A Class or an Expression returning a ClassReturns: A Boolean that is the result of testing the object against the Class. It lets you check the type of an object at run time.)
What operator checks the type of an OBJECT at run time?
generalization Inheritance allows you to reuse data and behavior from the parent class. If you notice that several classes share the same data and/or behavior, you can pull that out into a parent class. This is called generalization. For example, Customers and Employees are both people so it makes sense use the general Person class as seen below.
What refers to noticing that several classes share the same data and/or behavior, and pulling that out into a parent class?
Breadth First Search Breadth First Search uses logic similar to that of a depth-first search to explore topics, but stores future states with a queue. At each step, the search explores the option that has been waiting the longest, effectively branching out over different directions before going deeper. Says search at one level before going deeper
What search algorithm is used here?
Depth First Search Depth-first search is an algorithm that continues exploring, deeper and deeper, along a single path until it hits a dead end. The algorithm then backs up to the last branching point and checks other options. It maintains a list of future states to explore using a stack, always choosing the most recently inserted option to try next.
What search algorithm is used here?
Tree structures
What structures enable efficient access and efficient update to large collections of data
binary tree (binary tree is a finite set of nodes which is either empty, or else has a root node together two binary trees, called the left and right subtrees, which are disjoint from each other and from the root)
What term describes a finite set of nodes which is either empty, or else has a root node together two binary trees, called the left and right subtrees, which are disjoint from each other and from the root?
Generalization (EXPLANATION: Inheritance allows you to reuse data and behavior from the parent class. If you notice that several classes share the same data and/or behavior, you can pull that out into a parent class. This is called generalization. For example, Customers and Employees are both people so it makes sense use the general Person class as seen below.)
What term refers to noticing that several classes share the same data and/or behavior, that can be pull that out into a parent class?
A B D C E G F H I. A preorder traversal is a traversal that first visits the root, then recursively visits the left child, then recursively visits the right child. The first node printed is the root. Then all nodes of the left subtree are printed (in preorder) before any node of the right subtree.
What the preorder enumeration for the tree
A is-a relationship A class can extend only one superclass. Extending a subclass from a superclass creates an is-a relationship from the subclass to the superclass.
What type of relationship does extending a subclass from a superclass create?
super(theName) (EXPLANATION: The super(theName) in the Employee constructor will call the constructor that takes a String object in the Person class to set the name.)
What will call the constructor that takes a String object in the Person class to set the name?
1. Everywhere 2. In its own package EXPLANATION: A CLASS may be declared with the modifier public it which case that class is invisible to all casses everywhere. If a class has no modifier (the default also known as package- privates close parentheses, it is visible only within its own package) packages are named groups of related classes
Where does a CLASS that's declared with modifier PUBLIC seen? Where is a CLASS with no modifier seen?
D. Turtle t = new Turtle(100, 100, world1);
Which of these is valid syntax for creating and initializing a Turtle object in world1? A. Turtle t = Turtle(world1); B. Turtle t = new Turtle(); C. Turtle t = new Turtle(world1, 100, 100); D. Turtle t = new Turtle(100, 100, world1);
3. Every non-empty binary tree has exactly one root node
Which statement is false? 1. Every node in a binary tree has exactly two children 2. Every non-root node in a binary tree has exactly one parent 3. Every non-empty binary tree has exactly one root node 4. Every binary tree has at least one node 5. None of the above
class - A class defines what all objects of that class know (attributes) and can do (methods). You can also have data and behavior in the object that represents the class (class instance variables and methods). All objects of a class have access to class instance variables and class methods, but these can also be accessed using className.variable or className.method().
c
equals() •Used to compare objects Remember, we cannot use == for objects! •We need to override to compare the important fields of our classes See reading for more details, as there are some very important ones! •Don't always need to override See reading for details
equals()
•Always override if we override equals()!! •Gets the hash of all the relevant fields Need to be the same fields used in equals() •Important for certain data structures •Identical objects should have the same hash
hashCode()
toString()
toString() What INHERITANCE METHOD Tells how to give our class a text representation and is automatically called whenever we try to use an object with STRINGS One common way: System.out.println() •Should not print anything! Only return the String.