Final Superdeck Flashcards

(296 cards)

1
Q

Q1: Software development is all about learning a programming language.

A

False.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Q1: Object Oriented Programming is

A

A program consisting of classes and objects organized to manage the complexity of large-scale systems.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Q1: Procedural programming is

A

A program consisting of methods/functions calling each other.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Q1: A method ___

A

Implements behaviors relevant to the purpose of the system

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Q1: A field or attribute ___

A

Stores data relevant to the purpose of the system

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Q1: A container object

A

Data structure to store entities

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Q1: A control object

A

Organize computation or flow of the program

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Q1: An interface object

A

Facilitates communication between the system and the outside world

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Q1: An entity object

A

Model of a real-world thing in an application

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Q2: T/F A UML Use Case diagram is a type of behavioral diagram.

A

True.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Q2: In a UML Use Case diagram, what relationship is used in a situation where the execution of a use case ALWAYS involves the execution of an associated use case?

A

Include.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Q2: T/F A UML Class diagram is a type of behavioral diagram.

A

False.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Q2: Given three classes, plant, tree, and flower, which of the following best describes their relationship to each other?

A

Inheritance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Q2: Given two classes, House and Wall, where the House is a container of Wall objects, what describes their relationship?

A

Composition.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Q2: Given two classes, Book and Bookshelf, what best describes their relationship?

A

Aggregation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Q2: Given two classes, Hammer and Nail, what best describes their relationship?

A

Association.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Q3: What principle should be used to have a method have different behaviors depending on the class it’s invoked on?

A

Polymorphism.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Q3: What phrase/term is used to describe inheritance?

A

a ____ is a _____
i.e.
a cat is an animal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Q3: T/F Interface and inheritance are different names for the same concept.

A

False.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Q3: T/F. Polymorphism can be expressed in a UML diagram.

A

False.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Q3: What is the conceptual advantage to Polymorphism?

A

refactor ugly if and switch/case statements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Q3: What is the conceptual advantage to inheritance?

A

eliminate redundant code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Q3: What is the conceptual advantage to abstraction?

A

hide details and show the essentials; isolate the impact of changes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Q3: What is the conceptual advantage to encapsulation?

A

grouping related variables and functions together to reduce complexity and increase reusability

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q4: Is a String a primitive data type in Java?
No.
26
Q4: T/F All data types in Java are references to data allocated on the Heap.
False.
27
Q4: What Java data type is ideal for measurement data?
Double.
28
Q4: T/F. Both single and double quotes can denote a String literal in Java.
False.
29
Q4: What is the basic syntax for a for loop in Java?
for (int i=0; i<10; i++) { System.out.println("hello world"); }
30
Q6: What does toString() do in Java?
Lets programmers define a String representation of their class.
31
Q7: What is Validation in testing?
Any method to increase confidence in the correctness of a software system
32
Q7: What is an error?
The cause of an undesired behaviour or incorrect result
33
Q7: What is debugging?
Inferring the cause of undesired behaviour or incorrect results
34
Q7: What is a Fault?
An undesired behaviour or incorrect result
35
Q7: What is Automated testing?
The computer runs a script performing the tests
36
Q7: What is manual testing?
A human types some input into a program
37
Q7: What causes a fault?
An error.
38
Q7: What is coverage in testing?
How much of the code is tested.
39
Q7: What is a failure in testing?
The inability of the system to do what is required.
40
Q7: What is unintended behavior defined as?
A fault.
41
Q7: T/F It is possible for a code to have an error but cause no faults.
True.
42
Q7: T/F If there is no error in the code, there are no faults.
True.
43
Q7: T/F It's possible for a fault to be observed but no error to cause it.
Falst.
44
Q7: T/F If's possible for one error to produce multiple faults.
True.
45
Q7: When should testing code be removed from a class?
Never.
46
Q7: Is it okay to set private attributes to set up test cases?
Yes.
47
Q7: When should a regression test print the status?
Only when they fail. I.e. If all tests pass, they should print nothing.
48
Q8: What Java keyword indicates inheritance?
extends
49
Q8: T/F Polymorphism can be used with both inherited super types and implemented interface types.
True.
50
Q8: What are a few common methods inherited from the object class?
getClass(), equals(), toString()
51
Q8: T/F A downside of polymorphism is that once you have a container of the supertype, it is impossible to convert and object back to its original type.
False.
52
Q8: List of benefits of polymorphism.
Can reduce the amount of code that one needs to write. It can make code simpler and more concise. It reduces coupling. It can make code more flexible/adaptable.
53
Q8: What keyword is used to define that a class used an interface in Java?
Implements.
54
Q9: What data structure in Java can hold primitive data types?
Array (although arrays can also hold objects).
55
Q9: T/F Array lists have fixed size.
False.
56
Q9: T/F Arrays can only hold primitives.
False.
57
Q9: T/F TreeMap and HashMap can be used interchangably.
True, since they implement the same interface (although their performance may differ).
58
Q9: Which data structure is good for things being sorted and accessing things by their name?
TreeMap
59
Q9: Which data structure is good for needing to frequently inserting and removing from a a list.
LinkedList.
60
Q10: T/F Collections classes are defined using generic typing.
True.
61
Q10: T/F Generic types can be restricted to supertypes such as classes or interfaces.
True.
62
Q10: The comparable interface lets instances of the same class be compared with < and >.
False.
63
Q10: Java will automatically generate rules for comparisons between objects when implementing the Comparable interface.
False.
64
Q11: T/F after catching an exception, the program continues where the exception was originally thrown.
False.
65
Q11: T/F An exception should be thrown if a user enters bad/incorrect data.
True.
66
Q11: T/F An exception should be thrown if a regression test fails.
False.
67
Q11: T/F An exception should be thrown if a bug is detected in the program.
False.
68
Q11: T/F An exception should be thrown if a parameter violates a stated precondition.
True.
69
Q11: What is the best place to catch and handle an exception?
The method with enough information to effectively handle the exception.
70
Q11: T/F A try-catch statement can catch multiple different types of exceptions from the same try block.
True.
71
Q11: T/F code will NOT compile if you don't try to catch a potential checked exception.
True.
72
Q12: What is used to create a pop-up dialog box to prompt the user to enter text?
JOptionPane.showInputDialogue()
73
Q12: What is used in Java Swing to represent the application's window?
JFrame
74
Q12: T/F JFrame is a component.
False.
75
Q12: What is used in Java Swing to contain other components?
JPanel.
76
Q12: T/F we can create a custom window/frame by making a class that inherits from JFrame.
True.
77
Q13: In the event delegation model, what is a JButton?
An Event Source.
78
Q13: If you want to respond to a button click, what describes the process (as in the lecture).
Create a class that implements the ActionListener interface.
79
Q13: T/F An anonymous inner class can be defined without needing to assign the class name.
True.
80
Q15: T/F A goal of software design is to maximize cohesion.
True.
81
Q15: T/F A goal of software design is to maximize coupling.
False.
82
Q15: T/F A design pattern and algorithm are the same thing.
False.
83
Q15: What type of design pattern is the Singleton Pattern?
Creational.
84
Q15: What are the features of the Singleton Pattern?
Guarantees at most one instance of the class can exist in the system. Provides global access to the object instance.
85
Q15: T/F A static method can access both static and instance variables.
False.
86
Q15: What is done with the constructor in the Singleton Pattern?
It is made private.
87
Q16: What type of design pattern is the Factory Pattern?
Creational.
88
Q16: What is the main goal of the Factory pattern?
To abstract the creation of a class or a hierarchy of classes.
89
Q16: What is the issue of using strings as parameters to a factory?
Spelling errors are possible and easy to make.
90
Q16: What can a string be replaced with in the Factory pattern?
A Java enum
91
Q17: What type of design pattern is the Strategy Pattern?
Behavioural.
92
Q17: What is the main goal of the Strategy Pattern?
Define and encapsulate a family of algorithms to make them interchangeable in the program.
93
Q17: What is meant by the principle to program the the supertype, not an implementation?
Objects should be stored in the most general type possible.
94
Q17: What is meant by favor composition over inheritance?
In some cases, encapsulating behaviors as objects makes the program more flexible than using inheritance.
95
Q17: What are a couple in class/lecture/lab examples of candidates for the strategy pattern?
Choosing different routing algorithms in a map program. Equipping different attacks/abilities to a game creature.
96
Q18: What are the three layers in the Three-Layer Architecture?
Presentation, Domain, System.
97
Q18: T/F The Command Pattern can be used to coordinate between the presentation and the domain layer.
True.
98
Q18: T/F Each layer in the Three-Layer Architecture can only call methods in the layer below.
True.
99
Q18: T/F The Observer Pattern is used to update the databases whenever classes in the Domain layer change.
False.
100
Q18: T/F The Three-Layer Architecture promotes increased cohesion by forcing classes to be focused on smaller tasks.
True.
101
Q19: What type of design pattern is the Command Pattern?
Behavioral.
102
Q19: What is the main goal of the Command Pattern?
To encapsulate a method for the purpose of storing actions in data structures.
103
Q19: T/F The command pattern uses inheritance instead of composition.
False.
104
Q19: how are individual commands in the Command Pattern abstracted?
Commands all implement the same 'Command' interface.
105
Q19: What are a couple examples from class for candidates for the Command Pattern?
Managing a Queue of web requests. Implementing an 'undo/redo' system.
106
Q20: In the Observer pattern, what is the purpose of the Observer?
The classes that receive notifications/updates
107
Q20: In the Observer pattern, what is the purpose of the Subject/Observable?
The thing being observed
108
Q20: In the Observer pattern, what is the purpose of the Client/Driver?
Creates the objects and sets up the pattern
109
Q20: Recall the podcast distribution system example. What is the Observer, Subject, and Driver in this system?
Observer: The user that subscribes to the podcast and listens to it. Subject: The publisher/creator. They notify the observer of new releases. Client/Driver: The act of subscribing to the podcast.
110
Q20: What is the use of the UML 'ball-and-socket' notation?
Creating an interface to abstract/loosen coupling between two objects.
111
Q21: What design pattern is commonly used in the MVC architecture?
Observer pattern.
112
Q21: What is the responsibility of the model?
Perform the program's business logic. Update the View when the program's data changes.
113
Q21: What is the responsibility of the controller?
Interprets user input through ActionListeners. Call methods on the Model in response to user commands (i.e. translates events into messages for the model).
114
Q21: What is the responsibility of the View?
Generate ActionEvents in response to user interaction. Visually present data to the user.
115
Q21: What part of the MVC is the Observer?
The View.
116
Q21: What part of the MVC is the Subject?
The Model.
117
Q21: When does the Model send an update to the View?
Every time the data changes.
118
Q22: To make a custom GUI element/widget, which class do we need to inherit from?
JComponent.
119
Q22: What method needs to be overridden to make a custom GUI element/widget appear?
paintComponent.
120
Q22: What method needs to be called in order to update a custom GUI element/widget's appearance at runtime?
repaint
121
Q22: What type of object is passed into the paintComponent method as a parameter?
Graphics
122
Q22: T/F When writing code to draw a GUI element/widget, the color needs to be set for each shape drawn.
False.
123
Q23: T/F A Java Character Stream should be used to read in the data from a .png file.
False.
124
Q23: T/F A Java Byte Stream represents the data as a literal sequence of characters.
False.
125
Q23: Would a Text File or a Binary file likely be more compact?
Binary file.
126
Q23: Which Java class is used to read data from an input stream?
Scanner.
127
Q24: T/F A javax.swing Timer object will send an ActionEvent repeatedly with a specified delay.
True.
128
Q24: T/F A javax.swing timer automatically starts when created.
False.
129
Q24: As explained in class, what part of the MVC architecture was used to control the timer?
Controller.
130
Q24: As explained in class, what part of the MVC architecture was used to store the animation data?
Model.
131
Q25: Multithreading allows us to...
program multiple parallel threads of execution in a single program/process.
132
Q25: T/F if using two threads to manage a large amount of data, it will take exactly half the time of a single thread.
False.
133
Q25: What are a few reasons to use multithreading?
Improved design. Improved user experience. Improved performance.
134
Q25: What are the two given ways to use threads in Java?
Create a class that implements the Runnable interface. Create a class that extends Thread.
135
Q25: What is a given example of a race condition?
Multiple threads trying to write to the same file.
136
Q25: What is the solution to race conditions.
Lock objects.
137
Q25: What is Deadlock?
When multiple threads cannot proceed because they are waiting for locks from each other.
138
Q25: What is the solution to fixing/preventing deadlock?
Condition objects.
139
How does OOP handle complexity?
Decomposition.
140
Simple explanation for classes and objects?
Class: A blueprint. Object: An instance of a class.
141
Entity
Models real things
142
Container
A data structure to store entities
143
Interface
Communicates with the outside world
144
Control
Organizes computations
145
What is a concrete object?
I.e. People, buildings, equipment. Representative of physical objects.
146
What is a conceptual object?
I.e. organizations, agreements, abstractions. Represent concepts that aren't physical objects.
147
What is a state-change object?
I.e. Purchase, sale, birth. Represent events.
148
What is an interface object?
Handles communication between software and external entities. I.e. people and other hardware.
149
Types of methods.
Accessors/Getters. Mutators/Setters. Hybrid (discouraged in modern software).
150
Steps to software development process.
1. Requirements. 2. Design. 3. Implementation. 4. System Testing and Verification. 5. Maintenance.
151
What does UML stand for?
Unified Modelling Language.
152
What are the two kinds of UML diagrams?
Structural and Behavioral.
153
Types of behavioral diagrams?
Use Case, State, Sequence, Interaction.
154
Types of structural diagrams?
Component, object, class, deployment.
155
What is a Use Case Diagram?
Specifies the expected behavior, but not the exact method of making it happen (the what, but not the how).
156
What is a Primary Actor?
Triggers a use case to happen.
157
What is a Supporting Actor?
Someone/something that is indirectly involved with a use case. i.e. When a user (primary actor) tries to get money from an ATM, the Bank (supporting actor) has to verify they have enough money.
158
What is a Use Case?
Represents a system function. Verb+noun. do something Each actor must be linked to a use case, not every use case needs an actor.
159
Use case relationship for may conditionally execute the associated use case.
Solid arrow, dashed line, extend in double angle brackets.
160
Use case for will always execute the associated use case.
Solid arrow, dashed line, include in double angle brackets.
161
What is generalization?
Child inherits behavior and meaning of parent use case. Hollow arrow, solid line.
162
Inherit UML arrow.
Solid line, hollow arrow.
163
Implements UML arrow.
(Generalization). Dashed line, hollow arrow.
164
Association UML arrow.
Solid line. They call each other.
165
One way association arrow.
Solid line, line arrow (like an angle bracket on the end).
166
What is reflexive association?
A class may have multiple functions or responsibilities. Another box underneath to the lower right in UML.
167
Aggregation UML arrow.
Solid line, hollow diamond.
168
Composition UML arrow.
Solid line, solid diamond.
169
How do multiplicities work in UML?
Can specify a number: i.e. 1 A range of numbers: i.e. 1..* I.e. Teacher: 1 Student: 1..* 1 teacher may relate to many students/many students relate to 1 teacher.
170
Encapsulation principle.
Group related variables and functions to reduce complexity and increase reusability.
171
Abstraction principle.
Hide details, show essentials, isolate the impact of changes.
172
Inheritance principle.
Eliminate redundant code.
173
Polymorphism principle.
Refactor ugly if and switch/case statements.
174
4 principles of OOP.
Encapsulation Abstractions Inheritance Polymorphism
175
What is the substitution principle?
You can always use a subclass where a superclass is expected. I.e. Want an animal? A cat works.
176
What is dynamic method lookup?
Methods called are determined by the object, not the variable. I.e.
177
What is an abstract class?
Cannot be instantiated. I.e. Could make Animal abstract. Can have Animal variables, but they must really be concrete subclasses. I.e. Animal some_animal = new Cat();
178
What do Java executables run on?
A virtual machine.
179
What is the difference between Static and Dynamic typing?
Static Typing: Expressions checked at compile time. Must be fixed before running. Dynamic typing: Expressions checked at run time. Can run the program, but it may crash.
180
Benefits to Java running on virtual machines?
Safety: Can attack the virtual machine, but not the physical machine. Portability: "Write once, run everywhere." Can run on any machine with the JVM installed. More secure.
181
Does Java treat everything as objects?
No. Some values are stored on the heap as objects. Other are stored as bit sequences. I.e. all numbers.
182
What numeric operator is restricted to integers?
Modulo (%)
183
And, or, not in Java.
&& || ! Inherited from C.
184
How many times can you declare a variable?
Only once.
185
How many times can you initialized a variable?
Only once.
186
How to make a constant in java?
Use the keyword "final" This tells the compiler that no future changes are allowed.
187
How to you put a float in an int in Java?
You must explicitly type cast. i.e. int some_int = (int) some_float_value; Note that this truncates the float.
188
Java, if, else statements.
if (condition) { } else if (condition) { } else { }
189
Java do while loops?
do { } while (condition);
190
Steps to being able to use keyboard input in java.
import java.util.Scanner; Scanner in = new Scanner(System.in); ... = in.next(); or in.nextInt(); or in.nextDouble(); or .... in.nextLine(); is common for strings.
191
How to convert a string into another type?
I.e. For integers. Integer.parseInt(String s); Other examples: Float.parseFloat(String s); Double.parseDouble(String s);
192
String Comparison in java.
.equals() is best practice as I recall. That actually compares by value.
193
Types of errors.
Errors of Commission: Code you made has errors. Syntax errors. Minor logic errors. Errors of Omission: You did not write code for some behavior. No design. No plan.
194
What is defensive programming?
A practice of writing code to facilitate validation and debugging.
195
What is debugging?
Deducing the error from the fault.
196
What is validation?
Using techniques to increase our confidence in the code. I.e. formal proofs, informal reasoning, testing.
197
Can we test all possible inputs?
No. But we can cover every method, check the return values, check that they manage errors appropiately, etc.
198
What are the levels of testing?
Unit Testing. Integration Testing. System Testing.
199
What is Unit Testing?
Test each method individually.
200
What is Integration Testing?
Some methods working together. Limited combinations.
201
What is System Testing?
The entire application. Very time consuming.
202
What is bottom-up and top-down testing?
Bottom up: First test units that use no other units. Work up, moving on to other modules that use the already tested modules. Top down: Implement the top-level methods first. Write tests for them. Leave low level methods as stubs. Work down until complete.
203
When to use top-down vs bottom-up testing?
Top-down: Nebulous modules (or open-ended free-form projects). Bottom-up: Well understood modules (or well-structured assignments).
204
What is regression testing?
Comprehensive test scripts created during implementation. Rerun whenever a change is made. Easy to rerun and verify things are still correct. Never delete a test case, unless the method it tests is deleted.
205
How can we check the actual type of an object?
getClass() instanceof Casting
206
What is the cosmic superclass?
Object
207
List of basic data structures provided by Java.
Array LinkedList ArrayList TreeMap HashMap TreeSet HashSet
208
What is an array in Java?
A single block of memory with a fixed number of values accessed by integer index. All values of the same type. Can hold primitive or reference types. Can hold duplicates. Not part of the Java Collection Framework.
209
ArrayList
Memory space to contain values. Accessed by integer index. Can grow or shrink as needed. All of the same type. ONLY REFERENCE TYPES. Duplicate lists permitted. Methods like get add remove clear isEmpty size ...
210
LinkedList
Sequence of values accessed in order of all the same type and only reference types. Exactly as much space as needed. Exact same interface as List.
211
Maps
Stores key-value pairs. Called dictionaries in Python. HashMap (array-like) TreeMap (tree-like)
212
Example map methods?
put remove get
213
T/F every object has a built in hash function.
True. However, it is not optimal. Can be overridden to make a better implementation. This often needs the .equals method to be overridden too.
214
Sets in Java
Unordered collection. Can store, remove, and check values in sets. Only unique values. Like a map that only stores keys.
215
What can we do if we want to use a primitive where we must use a reference type?
Java provides wrapper classes. I.e. Interger Such as ArrayList() Java automatically box and unboxes between the primitive and reference types. I.e. can just give an int literal and java will figure out the rest.
216
Generics.
I.e. public class SomeCollection{ private ArrayList listofstuff; .... } When making SomeCollection, can specify the type i to use. Can also use restrictions. i.e. public class SomeCollection{ ....
217
What is an exception?
Any event that disrupts the normal flow of the program's execution. In Java, exceptions are objects.
218
What happens if an exception if caught and not handled by the program?
The program halts and an error report is displayed.
219
What did exceptions replace?
Error codes. Before, codes like -1, or -2,... would be returned to signify an error occurring. However, these could be ignored (which is problematic). Exceptions cannot be ignored.
220
How do you throw an exception?
throw new SomeKindOfException ("Message to accompany the exception");
221
Try catch statement
try { codethatcouldthrowexceptions } catch (ExceptionType exception) { do something } catch (Exception exception) { do something }
222
Types of exceptions.
Error. Internal JVM errors. Unchecked: Runtime exceptions. Caused by bad code (programmer's fault). Compiler doesn't force you to handle them. Checked: All other types. Not the programmer's fault. Compiler makes sure you handle these. Things like IOException, FileNotFoundException, etc.
223
What do you do when you write a method that could potentially throw a checked exception?
Use the throws clause. i.e. public Type someFunction(args) throws Some1Exception, Some2Exception,... Note: Only needed if it does not catch the exception, only if it throws one.
224
What is the finally clause?
In a try/catch block, it causes action to be taken whether or not an exception is thrown. I.e. Closing a file whether or not writing to it works.
225
How do you test exception?
Set up the test in a try catch block and intentionally do something that should cause an exception. If it isn't caught, print the error message for the test failing.
226
Tips for exceptions?
Throw Early. Better to handle it that use an imperfect fix. Catch Late: Only catch it if it can really be handled. Otherwise let it propagate until it finds something competent. Do not squelch: Don't do 'do-nothing' blocks. This only hides problems that could be serious.
227
JFrame
A single GUI window
228
JComponent
A single UI element (sometimes called a widget). Like JPanel, JTextComponent, JLabel, JButton, and many more.
229
JPanel
A JComponent that contains other Components
230
What is the event delegation model?
When the user interacts with an event source, it makes an Event object. An EventListener can be registered to the event source. Custom code can be added to the Event Listener to respond.
231
How do you register a listener to an event source?
ActionListener listener = new MyListener(); someEventSource.addActionListener(listener);
232
What are the types of inner classes in Java?
Nested Inner Class. Local Inner Class. Anonymous Inner Class.
233
How does a nested Inner Class work?
A class defined within another class. class OuterClass { ... class InnerClass { ... } } The Inner Class has access to all members of the outer class, including private data members and methods.
234
How does a Local Inner Class work?
Defined inside a method. Only exists in the scope of that method. public class SomeClass { ... void someMethod() { class LocalInnerClass() { ... } } }
235
How does an anonymous inner class work?
Defined exactly when needed without a name. Instead of a name, provide the class or interface the inner class should inherit or implement from. i.e. public interface SomeInterface { someMethod(); } public class OuterClass { public static void main(String[] args) { SomeInterface n = new SomeInterface() { void someMethod() { somecode } } n.someMethod(); } }
236
Cohesion
A class should represent a single concept. A class if cohesive if all methods and attributes are related to the concept the class represents. High cohesion is good.
237
Coupling.
Many classes having relationships to each other is high coupling. Low coupling is preferred.
238
What is a design pattern?
A way to structure some part of the application code. A general approach to some common design problems. Used to reduce coupling and increase cohesion.
239
What do design patterns consist of?
Intent: Brief description of problem and solution. Motivation: Further explains the problem and the solution the pattern makes possible. Structure: of classes showing each part of the pattern and how they are related. Code example: used to make it easier to grasp the idea behind the pattern.
240
Types of design patterns.
Creational. Structural. Behavioral.
241
What does the Singleton pattern do?
Guarantees that only one instance of a class can exist in a system. Provides global access to that instance form anywhere in the system.
242
How do you use the Singleton pattern?
Make the constructor private. Make the constructor not create more than 1 instance. All interactions with the single instance uses static methods. Make the constructor private. Use a private static attribute to store the object. Write a static method that returns this object.
243
What is a static attribute?
A single value shared by all instances.
244
What is a static method?
Used by providing the class name, not an instance/object. Can only use static attributes and local variables. Can not use instance attributes.
245
What is the factory pattern useful for?
Abstracting the object creation process to reduce coupling between specific classes and other parts of the system. I.e. We tell the factory we want a Cat, it gives us an Animal.
246
Factory UML.
Some module (like main/the driver) makes calls to the Factory. The Factory makes calls to the Class hierarchy (which is enclosed in a larger box).
247
How do you define an enum in Java?
public enum NameOfEnumType { ENUM1, ENUM2, ENUM3 }
248
Principles of the strategy design pattern.
Identify what varies and separate it from what is constant. Program to a super-type, not an implementation. Favour composition over inheritance.
249
What is the main idea of the strategy design pattern?
Turn behaviors into classes. A class contains (composition) SomeBehavior interfaces, the implementations of which contain methods. Can then call said methods like SomeBehavior.doThing(args);
250
What is the favour composition over inheritance principle?
Favour "has-a" over "is-a". I.e. Duck subclass is-a bird, and has-a flybehavior, instead of Duck is-a flying bird.
251
Difference between architecture and pattern?
Patterns are good for pieces. Architectures are for the whole system's organization. Less concerned with details, and more on the overall structure.
252
Presentation layer of Three-Layer-Architecture.
User interface. Calls methods in the Domain layer.
253
Domain layer of Three-Layer-Architecture.
Also called business layer. Gets the work done. Contains methods called by presentation layer.
254
System layer of Three-Layer-Architecture.
Also called Data layer. Collections (databases) needed by the Domain. Sometimes in another language or technology.
255
Advantages to the Three-Layer-Architecture.
Reduces coupling. Increases cohesion. Organization. Very useful for larger programs.
256
How can the Presentation and Domain layer be separated?
The Command Pattern.
257
When is the Command Pattern less useful?
Heavily interactable programs, such as games. They are better with MVC.
258
What is the basic thing the Command Pattern does?
Encapsulates requests as Command Objects. Hides the action behind a common interface. They independently perform their action. They can be tested automatically.
259
What is the Command Interface?
Make a new class for every unique request and implement the command interface. Write the code for the request in the method defined in the interface. Can then create a new object for each request as needed, store commands in data structures, etc. Essentially taking a verb (action) and treating it as a noun (thing).
260
Strategy vs. Command pattern.
Strategy is for how something should be done. Command is for what needs to be done.
261
What does the Observer pattern do?
Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Has a: subject/observable observer client/driver program
262
UML of Observer pattern.
Client makes calls to both subject and observer. Subject aggregates observers, and makes call to them (for push).
263
What does the Subject need in a UML?
Attributes: observers: ArrayList Methods: addObserver removeObserver notifyObservers
264
What does the observer need in a UML?
Methods: update
265
How can coupling be minimized in MVC?
Subject shouldn't know everything about the observer. Observer shoudn't know everything about the subject. The subject needs to notify the observer that data changes, but does not need to know the detail of who it's notifying. User an interface in the middle.
266
UML, minimized MVC coupling.
Using an interface in the middle (ActionListener). Ball and socket notation. source has socket, listener has ball. Write text for the name of the interface. i.e. "ActionListener"
267
MVC with Observer Pattern UML.
Controller aggregates View and Model, composed of a Listener (MyListener). MyListener connected to View with ActionListener interface (ball and socket). View connected to Model with Observer interface (ball and socket). Client calls controller, model, and view. Model implements Observable.
268
View - Observer
Implements Observer interface update() called by model when data changes
269
Model - Observable
Inherits form Observable class. addObserver() inherited model.addObserver(view) can be used after creation (in client) to let the view be notified when the model wants.
270
What do you do in the model after making a change to the data?
Call setChanged() notifyObservers()
271
How does the View Update?
It can request data from the model (pull via accessors) or be sent data directly (push). If pulling, the view needs to store the model as an instance variable. If pushing, use notifyObservers(Object arg) Which sends an object of our choice to all observers.
272
How to make a custom JComponent.
Make a class that inherits from JComponent. Override the paintComponent method. Write custom drawing code to customize how your component works.
273
What are some basic drawing commands?
g.setColor(Color) g.drawRect(int x, int y, int width, int height) g.fillRect(int x, int y, int width, int height) And many many more
274
What are the categories of steam objects in java?
Java Byte Streams: used to perform input and output for 8-bit bytes Java Character Streams: perform input and output for 16-bit Unicode characters.
275
What are the two ways to store data in a file?
Text format (character streams) Binary format (byte stream)
276
What makes Java binary files special?
They are platform independent.
277
Difference between InputStream/OutputStream and Reader/Writer?
Stream uses byte streams. Reader/Writer used Character streams.
278
How to read text from a file?
Scanner stream = new Scanner( new FileInputStream(filename)); Scanner behaves the same as if from System.in. Or: File inputFile = new File("filename"); Scanner in = new Scanner(inputFile);
279
How to output to a file?
PrintWriter out = new PrintWriter("filename"); If filename exists, it will be overwritten, if not, it will be created. out.println("line to print");
280
How to close a file in Java?
fileobj.close();
281
What package are timers part of?
javax.swing
282
How do the timers in Java work?
They fire an ActionEvent with a specified delay.
283
Creating a timer example.
MyActionListener L = new MyActionListener(); Timer t = new Timer(1000, L); t.start(); 1000 is ms
284
Processes vs Threads
Modern OS can run multiple processes at the same time. Each process can have multiple threads.
285
How can multithreading speed things up?
Divide a large job into many independent threads. Run all threads at the same time. Can also do things like separating the UI from the work.
286
Thread object methods.
run() start() (jvm calls run) wait() sleep(long ms)
287
How can you create a thread in java?
Extend the thread class and override run, or use the runnable interface and implement run() method.
288
What is a race condition?
The effect of multiple threads on a shared resource depends on the order in which they are scheduled.
289
What is an atomic action?
An action that cannot be interrupted until it is complete. At the machine code level, not the Java source level.
290
How can race conditions be handled?
Only allow one thread to access the resource at a time. This is called synchronizing. Access controlled with locks. When one thread has the lock for a resource, no other thread can access it until it releases the lock.
291
How do you use a built in Lock?
Put the synchronized modifier on a method (this only allows one thread to use the method at time). public synchronized void myMethod() {}
292
Lock object methods.
lock() try to obtain the lock, if successful, other threads cannot obtain it. If unsuccessful, the thread is paused. unlock() release the lock. other threads can try to obtain it now.
293
What happens if an exception is thrown between a lock and unlock?
lock it in a try statement, manipulate it in the final statement, unlock it
294
What is a deadlock?
occurs when no thread can proceed because they are all waiting for another to do some work first.
295
What is a condition object?
Allow a thread to temporarily release a lock and regain it again at a later time.
296