Final Flashcards
What is inheritance?
When a new class is derived from an existing class
The superclass _______ the subclass
The superclass generalizes the subclass
In the UML diagram what is used to describe a sub/super class relation?
an arrow pointing from the sub class to the super class
What does the subclass inherit from the superclass?
The subclass inherits all methods and fields
What does Overriding mean?
The subclass can have its own version of the super class’s method. The subclass method must have the exact same signature.
Can use ‘@Override’ to avoid errors.
What is the Java syntax for Inheritance?
public class Shape{
protected String name;
}
public class Circle extends Shape{
private double radius;
}
Benefits of class inheritance?
One superclass can be reused by many subclasses, allows for DRY code.
Improves the structure of large programs(hierarchical).
Modular Programming(encapsulation).
Given a class called Circle that is a subclass of Shape.
if Shape has a method called draw() and Circle overrides that method, how would you reference the parent class overridden method?
super.draw() can be used to call the overridden parent method
Can a subclass inherit private fields/methods from a method?
No, private fields and methods are only accessible to the class it is declared in
Are the following subclasses the same?
a. public class A extends B{
}
b. public class A extends B{
Public A(){
super();
}
}
yes they are equivalent, in the first example Java will implicitly imply the super. keyword to invoke the parent constructor.
In the UML diagram what is used to reference generalization?
an Arrowhead that points to the Superclass
Are superclass constructors inherited?
No, superclass constructors are invoked either implicitly or explicitly.
Explicitly using the super() keyword
Who do these visibility modifiers grant access to?
a. Public
b. Private
c. none
d. Protected
a. All objects anywhere
b. Only objects of the same class
c. All objects of the same package
d. Only objects of the same subclass( or same package)
So from most visibility to least visibility is the following:
Public -> Protected -> none -> Private
Where does the super() keyword when being referenced in a child constructor?
Also given a parent class Person which has a protected field String name. Write the syntax for a constructor of the child class called Student with private int gpa.
The first line of the child constructor
public Student(String name, int gpa){
super(name)
this.gpa = gpa
}
What is the difference between single and multilevel inheritance?
single level inheritance is when methods/fields are being inherited from one level above
Multilevel inheritance is when methods/fields are inherited from non parent classes(parents of their parents)
Given the following class and constructor
public class A{
private int num;
public A(int num){
this.num = num;
}
}
Would a child class of this need to call the constructor?
public class B extends A{
public B(int num, String name){
super(num);
this.name = name;
}
}
Yes when the parent class doesn’t use the default constructor you must explicitly invoke the super() constructor.
True or False?
When a derived object is created
the “super portion”
defined in the superclass
must also be
created and initialized?
True
What is the Object class? Also provide all methods it provides
All classes in Java are subclasses of the Object class whether they extend it or not.
toString()
equals()
getClass()
hashCode()
finalize()
…
Note: these methods can be Overriden
True or False?
All objects in Java instantiate the Object class.
True
Applying the final modifier to a class, who can inherit it?
How about applying final to one of its methods instead?
When applying final to a class, that class can no longer be extended(inherited).
When applying final to a method that method can no longer be overridden.
Why is the String class final?
The String class is immutable, therefore its objects cannot be modified after creation. Another reason for String being final is for security.
Given a subclass that extends an abstract class, what must the subclass do otherwise a Java error occurs?
Assuming the subclass is not also an abstract class, the subclass must implement all abstract methods from the parent class, like so:
in parent: public abstract double calcArea()
in child: public double calcArea()
What can hold abstract methods?
Abstract methods must be in an abstract class or interface, While an abstract class can hold non abstract methods
Can a subclass override a method and make it abstract?
yes
Can you instantiate a abstract class using the new keyword?
How about using it as a datafield?
You cannot instantiate an object of an abstract class
You can specify an abstract class as a data field.
Explain the relation between java.util.Calendar
and java.util.GregorianCalendar
Calendar is an abstract class, and gregeorianCalendar is a concrete subclass of Calendar. Contains the get method for objects of the Calendar class.
GregorianCalender is formatted like year,month, date where month parameter is 0-based. January is 0.
Why is an interface useful?
An interface is a blueprint that contains abstract methods and constants. The intent of an interface is to specify common behavior for objects.
note: Any fields declared in an interface are implicitly static and final
Examples of common interfaces(behaviours): Comparable, Edible, and Cloneable
Create an interface called Edible, that has a string method called howToEat
public interface Edible {
public abstract String howToEat();
}
Why are interfaces treated like special classes in Java?
Each interface is compiled into a separate bytecode file
Given the following interface, what is implicitly implied?
public interface T1{
int NUM = 1;
void p();
}
public interface T1{
public static final int NUM = 1;
public abstract void p();
}
methods are always abstract and fields are always static and final.
What does the Comparable interface consist of? and write the Comparable interface.
Also what does the method in it return?
Comes with the compareTo abstract method
package java.lang;
public interface Comparable<E> {
public int compareTo (E o);
}</E>
compareTo returns negative if object is less than o. returns 0 if object is equal to o. returns positive if object is greater than o.
Write a simple class called Dog that implements the comparable class and has a name field and has the compareTo method
public class Dog implements Comparable< Dog > {
private String name;
@Override public int compareTo(Dog other) {
What is the bytesize of the following datatypes?
a. int
b. long
c. float
d. double
e. char
a. 4
b. 8
c. 4
d. 8
e. 2
What are two classes we use that implement the Comparable interface by default.
The Integer and BigInteger Classes
Write code in the main method to compare integers 3 and 5 without defining objects.
System.out.println(new Integer(3).compareTo(new Integer(5))
//This should output a negative int
What does instanceof do and assume n is a Integer object write code checking n using instanceof
if(n instanceof Integer){
}
What does the Cloneable interface do, and what are it’s contents?
Cloneable interface is used to clone an object.
Here are the contents:
package java.lang;
public interface Cloneable {
}
Yes the cloneable interface is empty. An empty interface is known as a marker interface.
Write a class called Animal has a age field, has a explicit constructor and implements the cloneable interface.
public class Animal implements Cloneable {
private int age;
public Animal(int age) { this.age = age; } @Override public Animal clone() { try { return (Animal) super.clone(); } catch (Exception e) { throw new RuntimeException(e); } }
What is conflicting interfaces?
On rare occasions, a class may implement two interfaces with conflict information (e.g., two same constants with different
values or two methods with same signature but different
return type). This type of errors will be detected by the
compiler.
What is Polymorphism
Essentially the idea of polymorphism is that an object of a subtype can be used wherever it’s supertype is required.
Example1 : Animal a1 = new Dog()
or
public static void m(Object x){
}
m(a1)
Notice the m method is stated to take the Object type, but since Object is the superclass of all subtypes we can use any class to substitute.
How does dynamic binding work?
If an object invokes a method, Java will first search the most specific subclass, and then go up the hierarchy of more general classes(parents and parents of parents, etc) until it finds a class that defines the method.
Does Java support Multiple Inheritance?
Java doesn’t support traditional Multiple Inheritance, as attempting to extend more than one class will cause a compile error.
Multiple Inheritance can be achieved through Interfaces.
A java Class will implement interfaces, but what is it called when an interface is trying to use another interface?
Interface extends other interfaces. Note that an interface can extend multiple interfaces.
What does a Collection mean? and provide examples
A collection is a container object that holds
a group of objects, often referred to as
elements.
Sets
Lists(Arraylist, LinkedList)
Maps(Key value pairs)
Stacks(First in, Last out)
Queues(First in, first out)
PriorityQueues
What are some of the methods of the Collection interface?
clear() - removes all elements from this collection
add() - adds a new element to collection
addAll() - adds all elements from a collection to this one
remove() - remove element from collection
removeAll() - remove all elements that are in that collection from current collection
retainAll() - Only keep elements that are common in both collections
Note: AbstractCollection is an abstract class that partially implements Collection
Given Collection A and Collection B,
how would you:
a. Remove all elements from A?
b. Add all elements from B to A?
c. Remove all elements in A from B
d. Only keep common elements that both A and B have
a. A.clear()
b. A.addAll(B)
c. B.removeAll(A)
d. A.retainAll(B)
What are the classes of the List interface? and common methods?
ArrayList and LinkedList
Common Methods:
add(index, element)
addAll(index, collection)
remove(index)
set(index, element) - changes value of index(removes old value)
indexOf(element)
lastIndexOf(element)
subList(fromIndex, toIndex) - creates another list based on indexes, inclusive.
Given the following:
List< String> list
Assuming it has values how would you output all elements of the list traversing forward?
ListIterator< String> iterator = list.listIterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
Given the following:
List< String> list
Assuming it has values
How to traverse the list backwards using ListIterator?
ListIterator< String> iterator = list.listIterator(list.size());
while(iterator.hasPrevious()){
System.out.println(iterator.previous());
}
Given two versions of the same class
A. public class Circle{
double radius
public boolean equals(Circle c){
return this.radius == c.radius
}
}
B. public class Circle{
double radius
public boolean equals(Object o){
return this.radius == ((Circle)o.radius)
}
}
If this is the main:
Object o1 = new Circle();
Object o2 = new Circle ();
System.out.println(o1.equals(o2))
What would output of versions A and B be?
A. would be False
In the main o2 is defined as Object class, so with polymorphism it can still be passed in as a Circle, when being compared using == , without being casted using (Circle) the == operator returns false
B. would be True
since the o2 being passed into the equals method is casted as Circle, the comparison would be between two of the same classes.
What is an inner class?
A class in a class, the inner class can use private fields/methods of the class it exists in.
It is compiled like so: OuterClass$InnerClass.class.
An inner class can be declared static
True or False?
If a method is declared private in the superclass, you may declare the method protected in the subclass.
True,
the methods would be unrelated to each other, not overridden. The private modifier would prevent the subclass from inheriting it, allowing the subclass to create it’s own protected version of the method.