final Flashcards
what are the 9 forms of inheritance?
- specialization
- specification
- construction
- generalization
- extension
- limitation
- containment
- variance
- combination
Forms of Inheritance
what is specialization?
- subclass is a specialized form
- subclass may add more or override parent methods
eg. Honda is a Car
In JavaScript how are constants made? How are they accessed?
Constants are made by making a method with “get”
Class constants use the static keyword and are accessed using the name of the constructor.
eg. static get COST_FACTOR() { return 1.5; }
ClassName.COST_FACTOR();
this.constructor.COST_FACTOR; //can also do this
Forms of Inheritance
what is specification?
used to guarantee common methods of interaction
- parent is used to describe required behaviour, using abstract methods
- focus is filling the holes left incomplete by the parent
what is the principle of substitution?
(aka the Liskov Substitution Principle)
If we have 2 classes A and B such that B is a subclass of A: it should be possible to substitute instances of class B for instances of class A in any situation with no observable effect
Interfaces can be seen as a form of inheritance. Which one?
specification
Forms of Inheritance
what is construction?
Child inherits most or all of its functionality from parent, making changes to the behaviour to build/construct something different
- Principle of substitution does NOT hold
- Subclass is not a subtype, can’t be substituted
The whole idea of an object is to provide ___________ of the representation of the state and behaviours of something
It’s very important to be able to hide implementation details
- if an object defines a field, it should …
- don’t assume subclasses will…
- these things lead to increased…
encapsulation
- define how it can be used/accessed/modified
- use it properly
- independence and reliability
Forms of Inheritance
what is generalization?
A subclass modifies the behaviour of the parent to make a more GENERAL kind of object (opposite of specialization)
- generally want to avoid this
C++
class X: {}
- public: visible to…
- private: visible only to…
- protected: visible in…
- public: visible to any user of a class X object
- private: visible only to X’s own member functions
- protected: visible in X’s member functions and member functions of subclasses of X
Forms of Inheritance
what is extension?
Extension only adds new methods to those of the parent, rather than overriding anything (inherited behaviour does not change)
Why use private at all when protected seems to give us what we want?
Private gives us better security and reliability, and better control of data locally
protected gives away too much power
nothing stopping subclasses from managing the data/methods in unintended ways
Forms of Inheritance
what is limitation?
- Behaviour of subclass is smaller or more restrictive than parent (excludes some operations)
which one of these is done by default if no access modifier is used?
class B: public A
class B: private A
class B: protected A
private
In C++, The status of the base class defines…
what the status of its members are in the inherited class*
*status only changes if it’s getting more strict
Forms of Inheritance
what is containment?
has-a relationship
private inheritance is essentially a ______ relationship
has-a
private and protected inheritance do not allow…
substitution / polymorphism
Forms of Inheritance
what is variance?
- > =2 classes have similar implementations but don’t seem to have a hierarchical relationship between the abstract concepts they represent. We arbitrarily pick one to be the subclass of the other
C++ Friendship
friends have access to…
the class’ private members and makes it part of the object’s scope (allowing it to use the object’s members)
class Node {
friend class GenericList;
}
* all of GenericList’s members are now friends of
Node and can access…
Node’s private members
If class B is a friend of class A, who decides that?
Class A.
the class giving up control of its members is the class that defines who its friends are
Friendship is NOT:
* __________
* __________ (the friend of my friend is not my friend!)
* __________
- inherited
- transitive
- reciprocal
Forms of Inheritance
what is combination?
A class requires a combination of features from >=2 parent classes
- This requires multiple inheritance
Friendship is not a way to fix a bad OO implementation. Why?
It gives away a lot of power and can possibly defeat the purpose of encapsulation when not used properly
In Java, an _____ makes reference to already
compiled byte code stored outside of your program,
and allows a dynamic search for it
import
Example: a sessional instructor could be a graduate
student and an instructor at the same time
- SessionalInstructor class would extend
GradStudent and Instructor classes
What form of inheritance is this?
multiple inheritance
Java 0rganizes classes into packages
- Partly for the sake of
- and
grouping code logically – putting a group of classes that serve a common purpose together
encapsulation: there are mechanisms that can allow broader access between items in the same package, whether they are subclasses or no
* i.e. serving much the same purpose as a set of
friend declarations in C++
package MyPackage.MyClassesA;
public class MyClass1 { …..}
class MyClass2 {…..}
- The name of this package is __________
- Its location is directory ________ inside directory __________
MyPackage.MyclassesA
MyClassesA inside directory MyPackage
How do package directories get created?
You need to create the folders and ensure the classes are compiled in the right folder
it is up to you to place the source in the appropriate place
- In dynamic languages (e.g. JavaScript, Python),
variables have dynamic types – a variable’s type
changes to suit what’s in it
what does this mean for dynamic class binding?
can assign subclass objects to superclass variables AND the reverse
- only because there is no concept of a static type anymore
To allow polymorphism, a hidden tag is stored to allow identification at _______
run time
Implementing a Set class by inheriting from a general List class
* Set inherits all List functionality
* ensure duplicates don’t go in the list
What form of inheritance is this?
Construction
if no protection modifier is used in Java what do we get by default?
package private
- in our assignments it essentially makes everything public
- if using packages properly then anything inside the package has access
Anything not belonging to the named package belongs to…
the default package (unnamed)
what are the 5 good forms of inheritance?
- specialization
- specification
- extension
- containment
- combination
Java’s Protection Modes
- Public: Visible to…
- Protected: Visible to…
- Private: Visible only to…
- Blank (package access / friendly access / package protection / package private): visible to…
Public: Visible to anybody anywhere
Protected: Visible to the class in which it’s defined,
and its derived subclasses, AND classes in the
same package
- a lot more insecure than you would at first think
Private: Visible only to the class in which it’s defined
package private: visible to itself, and other
classes in the same package, but not from derived
subclasses
Does B have access to x?
(Package P1)
ClassA {
int x;
}
(Package P2)
ClassB extends ClassA {
…
}
No.
x is package private and classB is in a different package
in Java, protected members are accessible by…
subclasses AND classes in the same package
Suppose UnprintableCharAtom has a CharAtom x as
a data member
* x can be private
* We just don’t allow access to print() method
what form of inheritance is this?
containment
________ is often seen where we are working with a base class that can’t be modified (eg. library code)
generalization, limitation, variance
package MyPackage.MyClassesA;
public class MyClass1 { …..}
class MyClass2 {…..}
one of these are public – i.e. their existence will be known to…
anybody importing the package once it is compiled
package MyPackage.MyClassesA;
public class MyClass1 { …..}
class MyClass2 {…..}
When run through the java compiler, what .class files and .java files will be created?
MyClass1.class
MyClass2.class
MyClass1.java
- since MyClass2 is in the same file, it doesn’t need its own .java file
What is a Java Interface?
A Java facility for guaranteeing an object will be able to interface with other objects in a defined way (by forcing it to implement abstract methods) without actually using any traditional inheritance
An Interface in Java is a structure that lists (public)
methods that are to be required by classes that
implement the interface
- It has no concrete methods*
*possible with default methods
In an interface every method is automatically _________ and _________
public and abstract
What form of inheritance is used with interfaces?
specification
interfaces specify which methods must be used by any class that implements the interface
what’s the difference between an abstract class and an interface?
Classes extending an abstract class are related through a hierarchy; those implementing an Interface can be otherwise totally unrelated
e.g. taking a list and making other data structures out of it via inheritance (e.g. a queue, a stack)
what form of inheritance is this?
limitation
If we want to make a linked list where the data utilizes interfaces Printable and Comparable what should we do?
define an interface that is a child of any interface you want to implement (Printable and Comparable in this case), and then use that interface for you Node data
interface ListItem extends Comparable, Printable {}
How come multiple inheritance isn’t violated when implementing multiple interfaces
we aren’t inheriting anything, just receiving more demands
*one exception to this is using default methods
can you make an instance of an interface?
No. You make an instance of whatever class
implements the interface
it’s just a collection of methods that have to be implemented by somebody else – no memory to allocate
Can the methods in an interface have code? Should they?
Typically the should not, and can not
But, default methods allow you to
eg. default void doSmth() { … }
- an implementing class can keep the default behaviour or change it
when are default methods useful?
when you want to add a new method an old interface, but you want your old code to keep working (your old code was written for the older version of the interface)
what problem does using default methods create?
you get problems related to multiple inheritance
if a class implements two interfaces that both define different version of a default getIt() method then you will get a compile-time error
*can fix if the class defines a new behaviour for getIt()
What happens if:
* Class Child extends class Parent
* Class Child implements interface Int1
* Both Parent and Int1 provide code for method foo()
The version from the parent class overrides the default behaviour provided by Int1
Extends has priority
When defining a subclass that also implements an
interface, ________ goes before __________
implements/extends
public class Child extends Parent implements Int1 {}
default String toString() {return “Hello!”;}
does this work? why or why not
Can’t override methods from Object with a default method in an interface
Gives error at compile time:
error: default method toString in interface Int1 overrides a member of java.lang.Object
what kind of methods can be defined with code in an interface
default methods and static methods
What are nested Interfaces? When/why would you use this?
when you declare an interface within another interface
used to group interfaces that have a similar/related goal or meaning
- e.g.
interface Printable {
void print();
interface Testable { //nested interface
void test();
}
}
how do you refer to a nested interface?
eg. Testable interface is nested inside Printable interface
To refer to a nested interface, you must specify the name of the outer interface, followed by a dot
class MyTest implements Printable.Testable {}
Does a nested interface inherit requirements of its outer interface?
No
JavaScript is a ________ language
C++ and Java are properly referred to as ____________ languages
dynamic
semi-static
JavaScript has dynamic variable typing. What is that?
What is a special case of this in Java and C++?
a variable’s type is whatever it currently contains - which means it usually has no type declaration
in Java/C++ - putting an instance of a subclass in a superclass type variable
dynamic languages access all memory via ________ internally
pointers
dynamic languages are usually __________ rather than compiled
interpreted
what are the 3* forms of inheritance that should be avoided
*(3 and a half)
- construction
- limitation
- variance
- generalization
in some way, the programmer must play the role of
the compiler in dynamic languages. why?
When a program’s state can change so drastically at runtime, it means a lot of runtime checking that the programmer must do
Does JavaScript require semicolons at the end of statements?
no, but we still use them by convention
how do you declare a variable in JS?
let keyword
let x = 5;
let myString = “hello”;
Using “let” gives us block scope. which means:
variables defined in a block are only accessible inside that block
Does B have access to x?
(Package P1)
ClassA {
protected int x;
}
(Package P2)
ClassB extends ClassA {
…
}
yes
in Java, protected means accessible by subclasses as well as classes in the same package. ClassB is a subclass of ClassA
In JS, at the top of your code (first line), you should put what? why?
“use strict”
- This adds more restrictions
- want all the error messages we can get since there aren’t many
eg. preventing the use of undeclared variables
x = 75; // ReferenceError: x is not defined
In JS, you can use the _______ operator (not a method) to get the type of what is stored in a variable
typeof
What happens if you pass too few parameters to a JS function?
Too many?
Too few: The variables not assigned a parameter will get the value “undefined”
Too many: Extras get put in the arguments array which can be accessed
- console.log(arguments); // print all args
All primitive types in JS are __________
- if you assign the value of a variable to another one, a copy will be made
immutable
Remember that JS is weakly typed.
- 0 == “0” //true or false?
- 0 == false
- 0 === “0”
- “” == 0
- undefined == null
- “0” == 0
- 0 === false
- “0” == “”
- ‘’ == false
- undefined === null
- 0 == “”
- true
- true
- false
- true
- true
- true
- false
- false
- false
- true
- true
In most cases, you should use === and !== instead of == and !=
why?
- JS is weakly typed
- === checks strict equality
- does the comparison without type conversion
Does JS need a main function?
no but by convention we create one and then run it as the only executable line in our script
Say generic list provides insert@front, insert@end,
remove@front, remove@end
creating a stack out of this would be limitation. Whats the appropriate solution?
The appropriate solution is using containment (i.e. build the list, then use it as a data member inside a stack)
The stack can then use the functions from list that it needs to do push and pop and leave anything else alone
how do you create a function in JavaScript?
by using the function keyword
function myFunction(param1, param2){
}
(dont need it for class method definitions)
how to make a constructor for ClassB that is a subclass of ClassA
- classA takes int param
- classB takes string
in all three languages
Java:
ClassB(int x , String s){
super(x);
this.s = s;
}
C++ .cpp:
#include <string>
ClassB::ClassB(int x, std::string s) : ClassA(x) {
this->s = s
}</string>
JS:
constructor(x, s){
super(x);
this.#s = s;
}
in JS instance variables are _______ by default
private/protected/public?
public
in JS, instance variables that are public don’t need to be declared. When are they created?
What about private variables?
- they are created when used (either in the
constructor [best] or any other method) - they don’t exist until that code is executed
private variables must be declared
- use #
eg.
class MyClass {
#id; // declaration needed cuz private
constructor(id) {
this.#id = id;
}
}
How do we create multiple constructors in JS?
Technically it’s not allowed (no overloading)
we have to simulate it using the args array
// null constructor and constructor with one param
constructor() {
if(arguments.length == 0) {
…
} else if (arguments.length == 1) {
…
}
}
What happens when you try to overload a function in JS? How can you simulate overloading?
The version furthest down gets used.
Must simulate using the args array, same as how we simulate having multiple constructors.
How is getting/setting different in JS?
special keywords “get” and “set”
- don’t need parentheses when calling
eg.
// in class MyClass
get id() {
return this.#id;
}
// in main
let mc = new MyClass(1234);
console.log(mc.id); //using getter
How is a private class variable accessed in JS?
through the class name, even within the class
- class methods are also accessed through the class name
class MyClass {
#id;
static #counter = 1; //private class variable
constructor(){
this.#id = MyClass.#counter++;
}
}
How do we do class constants in JS?
- cant use const keyword with class variables
- solution: make getter static method
static get HOURS_PER_DAY(){
return 24;
}
//accessing the constant
console.log(MyClass.HOURS_PER_DAY);
// because we used the “get” keyword it really looks like we’re accessing a constant
what’s another way to make objects in JS that you can’t do in Java/C++
how is it different from how we normally create objects?
you can make single instance objects in JS like this:
- methods can be defined inside
- “function()” is actually not necessary
aChair = { material: “wood”, weight: 5.5
print: function() {
console.log(“Weight: ” + this.weight);
}
}
- only get single instance
- no class model defined that can be reused
What if you forgot something in your unnamed object in JS?
You can add fields and methods to it after it’s definition
- “function()” is required in this case
These new members would only exist after the code that adds new members
eg.
aChair.getWeightInLbs = function() {
return this.weight * 2.205;
}
How can you update a class in JS?
use .prototype
- Note that usually, if you have access to the class definition, you would want to make any permanent changes there
- can be used to add to built in classes such as Array
eg.
function main() {
//add field
MyClass.prototype.name = “NoName”;
//add method:
MyClass.prototype.getName = function(){ return this.name; };
}
let a = new MyClass(3333);
let b = a; //a and b are pointing to the same memory
console.log(a == b); //true or false?
true. compares pointers
Object.assign can be used to copy objects
- use getPrototypeOf to copy the methods as well
function main() {
let mc = new MyClass(1234);
let mcCopyProto = Object.assign(Object.getPrototypeOf(mc), mc);
This will work if the fields in MyClass are public. So does Object.assign create a deep copy?
not a true deep copy
- Object.assign (with or without getPrototypeOf) still does not deep copy nested objects (objects contained within objects)
If you want to separate your classes into different files, they will not get detected automatically by Node.js, even if they are in the same folder
You will need 2 things:
- module.exports -> to export a class (make it available to be “imported”)
- require -> to import what is exported in another file
In JS _______________ are not inherited
instance variables
- they are created when the code creating them is
run, i.e. when calling the super constructor - Only the methods are inherited
What happens if you try to access a private field from a parent class?
class GradStudent extends Student {
#thesis;
constructor(name, sId, thesis) {
super(name, sId);
this.#thesis = thesis;
this.#name = “Jane”; //?
}
}
SyntaxError: Private field ‘#name’ must be declared in an enclosing class
- JS thinks you want to define a new field but private fields must be declared
In JS you can assign a super class in two ways:
- using extends like Java
- at runtime using prototype
The following will declare that MyClass is a subclass of
OtherClass:
MyClass.prototype.__proto__ = new OtherClass();
- MyClass will now inherit any methods from OtherClass
Overloading in JS
In some cases, it might make sense to use default parameter values to simulate overloading
- In the example below, parameter message will be initialized to “Hello” if…
- Similarly, parameter number will be initialized to 0 if…
myMethod(message = “Hello”, number = 0)
{
//body
}
- no parameter is used when calling the method
- less than 2 parameters are used when calling the method
How is overriding different in JS?
overriding a method in JS doesn’t require using the same parameters in the signature: only the same method name
How does shadowing work in JS? Think about private instance variables vs public. How about methods?
shadowing only occurs in private instance variables
shadowing is not possible with public variables because fields are not inherited
shadowing is not possible with methods because there is no tool to turn polymorphism on/off
What is duck typing?
“if it walks like a duck and quacks like a duck, it probably is a duck”
- duck typing is when your main concern is if the object contains the required method
- can verify using typeof
eg. if (typeof s1.print == “function”)
polymorphism is always on in JS. why?
no static type. always getting the version of the dynamic type
Why is instanceof less useful in JS?
- no need to cast variables
- care more about if it has the right method rather than if it belongs to the right class (duck typing)
what are the goals of an abstract class?
- No instantiation possible
- Enforce requirements on the subclasses (required methods)
- Potentially have some code too that can be inherited
How do you make an abstract class in JS?
simulate
- make instantiation impossible
- throw new Error() in constructor if this.constructor.name === “ThisClassName” - create abstract methods
- throw new Error() in any method you want to be abstract
- this way the child class must override the method to get rid of the error message
What are mixins?
- a way to include outside code in a class without
using inheritance - it’s used to bring in methods (mostly) and constants
to different classes that are unrelated - To add a mixin to a specific class, you need to add it to the prototype using Object.assign
There is the potential for ambiguity in interfaces and multiple inheritance. How might this happen? How does the programmer handle it?
What’s a similar situation in C++?
- If two interfaces provide the same constant, there can be ambiguity and we have to prefix it with the interface name
- doesn’t apply to methods (unless they both have the same default method)
- in C++, we can get ambiguity with methods when using multiple inheritance. We have to handle it in a similar way. Use fully qualified names (e.g. A::foo())
allowing multiple inheritance leads to two complications:
- Implementation difficulties (how is the compiler going to deal with this?
- it’s not the programmer’s problem, it’s the language’s responsibility, but good to know - Problems with ambiguities
What is the diamond problem
How do you deal with the ambiguity it creates?
When you have a class hierarchy that looks like a diamond. The bottom class (C) will have two versions of the stuff from the top class (A)
Can deal with it by explicitly saying which version we want in the bottom class:
B1::a = 6; // B1’s copy of a
B2::a = 7; // B2’s copy of a
Can use virtual inheritance (let the compiler solve the problem)
class B1: public virtual A {…}
class B2: public virtual A {…}
- C becomes responsible for initializing A’s stuff
What does virtual inheritance mean?
there may be more than one appearance of the superclass, and if that is the case, only one copy should be included
There are special rules to ensure that virtual base class constructors/destructors are only called once per object (2)
- virtual base classes are constructed before all other subclasses
- constructors for virtual base classes anywhere above in the hierarchy must be called by the constructors of each derived class
* this is one time when a subclass can directly call a grandparent’s constructor
How do we simulate multiple inheritance in Java
(1 good way, 2 bad)
- use interfaces
- Duplicate code: you can inherit from one of the two classes you need to be a child of, and duplicate the code of the other (retain one hierarchy, but not both)
- Use Limitation: insert objects lower into a hierarchy, and override methods that you don’t want with empty bodies
Why is duplicating code a bad way to simulate multiple inheritance?
one of OOP’s goals is to reuse code
Why is using limitation a bad way to simulate multiple inheritance?
limitation breaks the principle of substitution
- but in some cases it’s one of the only choices
How does the compiler deal with multiple inheritance? For example, if C extends A and B
This is how an instance of C would look internally:
_________
|Tag: C |
|A’s stuff|
|B’s stuff|
|C’s stuff|
‾‾‾‾‾‾‾‾‾‾‾‾‾
Where would A pointers enter? B? C?
- Need additional checks
- Ensure that we access data from the appropriate entry points for each type
_________
|Tag: C |
|A’s stuff| entry point for A* or C*
|B’s stuff| entry point for B*
|C’s stuff|
‾‾‾‾‾‾‾‾‾‾‾‾‾
B* shouldn’t enter at the top because it doesn’t know about A’s stuff
In a Java interface There are no true data members (not in the sense of inherited variables anyway) – how come?
any data members we declare are implicitly public, static, and final, i.e. class-level constants
A powerful feature of Interfaces is that they can act like a _____, just as a class does
type
can have variables of type Measurable, Printable, Viewable, etc.
T/F
In JavaScript, parameters are more of a suggestion
true
it doesn’t complain if you have too few or too many
Name the type of inheritance
class Adult{…}
class Student{…}
class GradStudent : public Adult, public Student{}
Combination
Name the type of inheritance
abstract class 2DShape{
public abstract double calcArea();
}
class Circle extends 2DShape{
…
}
specification
Name the type of inheritance
class Walker{
public void walk() {…}
}
class Runner extends Walker{
public void run() {…}
}
extension
Name the type of inheritance
class Feline{…}
class Cat extends Feline{…}
specialization
Name the type of inheritance
class Node{…}
class MyList{
private Node first;
public Node getFirst(){
return first;
}
}
containment
Name the type of inheritance
class Car{
private int age;
public int getAge()…
public void setAge()…
public void startCar(
…code to start car…
)
}
class EnginelessCar extends Car{
public void startCar(){}
}
limitation
Name the type of inheritance
class Tiger {…}
class Tiger extends Lion {…}
variance
Name the type of inheritance
class Flower {…}
class Plant extends Flower {…}
generalization