350 - Object oriented programming

0.0(0)
studied byStudied by 2 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/173

flashcard set

Earn XP

Description and Tags

Midterm/Final

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

174 Terms

1
New cards

How do you represent an inheritance in a UML class diagram?

solid line with a triangle (IS-A)

2
New cards

How do you represent an interface in a UML class diagram?

dashed line with a triangle.

3
New cards

How do you represent an association in a UML class diagram?

solid line between two classes that indicates a relationship between them.

4
New cards

In a UML diagram if a piece of text is in italics, then it’s what?

Abstract

5
New cards

In a UML Diagram, when there is an arrow pointed in one direction what does that mean?

That indicates a directed relationship.

6
New cards

In a UML class diagram, what does a filled diamond mean?

It represents a composition relationship, indicating that one class is a part of another and cannot exist independently.

7
New cards

In a UML class diagram, what is aggregation (weak)?

Represented as an open diamond, indicating a whole-part relationship where the part can exist independently.

8
New cards

In a UML diagram, public is represented as what?

+

9
New cards

In a UML diagram, private is represented as what?

-

10
New cards

In a UML diagram, protected is represented as what?

#

11
New cards

In a UML diagram, package is represented as what?

~

12
New cards

what does the top compartment of a UML class contain?

Class name and what type of class it is

13
New cards

what does the middle compartment of a UML class contain?

Attributes and their visibility

14
New cards

What does the bottom compartment of a UML class contain?

Methods and their visibility

15
New cards

What is Javadoc?

Javadoc is a tool provided by Java that automatically generates HTML documentation from specially formatted comments in Java source code.

16
New cards

What do Javadoc comments begin and end with?

/** and end with /

17
New cards

In Javadoc, what tag describes method parameters

@param

18
New cards

In Javadoc, what tag describes the method’s return value?

@return

19
New cards

In Javadoc, what tag specifies exceptions thrown by the method?

@throws

20
New cards

In Javadoc, what tag links to other classes, methods, or fields?

@see

21
New cards

In Javadoc, what tag marks methods that should no longer be used?

@deprecated

22
New cards

In Javadoc, what tag adds an "Author" entry with the specified name-text to the generated docs?

@author

23
New cards

The first sentence of a Javadoc comment is what?

Summary sentence that provides a brief overview of the method or class's purpose.

24
New cards

In Anti-Patterns, what is a God-Object?

A class or module that becomes excessively large and takes on too many responsibilities.

25
New cards

In Anti-Patterns, what is an Anemic Domain Model?

When domain objects lack behavior or business logic and serve primarily as data containers.

26
New cards

In Anti-Patterns, what is Spaghetti code?

Characterized by tangled and poorly structured logic, often resulting from ad-hov development without proper planning or design.

27
New cards

In Anti-Patterns, what is copy-paste programming?

Involves duplicating code instead of abstracting common functionality into reusable components.

28
New cards

In Anti-Patterns, what is constant interface?

Where an interface is used solely to declare a set of consistent variables instead of using a class to define constants.

29
New cards

In Anti-Patterns, what is “Not Invented Here”?

The tendency of developers to reject existing solutions or libraries in favor of building their own from scratch

30
New cards

In Anti-Patterns, what is “Feature Envy”?

When a method or function in one class excessively accesses the data or methods of another class, rather than relying on its data and behavior.

31
New cards

In Anti-Patterns, what is “Dead Code”?

Unreferenced or unreachable portions of the codebase that no longer serve a purpose

32
New cards

In Anti-Patterns, what is “Magic Numbers”?

Hard-coded numbers that are scattered throughout the codebase without any explanations.

33
New cards

In Anti-Patterns, what are “Hardcoding configurations”?

Hardcoding configuration settings, such as database connection strings or API endpoints, directly into the codebase make it inflexible and difficult to manage across different environments.

34
New cards

In Anti-Patterns, what are “Code Smells”?

indications of potential problems in the codebase, such as long methods, large classes, or excessive comments.

35
New cards

In Anti-Patterns, what is “The Swiss Army Knife”?

when a software component or module is designed to be overly general-purpose and flexible, trying to accommodate various use cases and requirements. This results in bloated code, increased complexity, and decreased performance.

36
New cards

True or False. Monostate defines a “conceptual singleton”

True

37
New cards

Why is monostate not a true singleton?

Because it allows multiple instances to exist while sharing the same state.

38
New cards

What is the difference between power type and Flyweight design pattern?

Both are designed to eliminate the need for duplicate objects, but the Flyweight pattern focuses on sharing objects to support a large number of similar objects efficiently, while the Power Type pattern enhances type safety by creating subclasses for specific behaviors.

39
New cards
<p>What design pattern is shown in the UML?</p>

What design pattern is shown in the UML?

Strategy because the interface delegates behaviors to the correct implementation.

40
New cards
<p>What design pattern is demonstrated in the image?</p>

What design pattern is demonstrated in the image?

Power Type I know this because the code splits the class into two classes. One for unique data and another for shared, unchanged data to optimize memory usage.

41
New cards

What 2 patterns help to manage state and data more efficiently?

Monostate and Power Type. Monostate because it allows a shared state across multiple instances, and Power Type because it reduces memory waste and maintains consistency across objects that share common data.

42
New cards
public interface WeatherSubject {
    void registerWeatherObserver(WeatherObserver wo, double percentChange) throws SomeException; // keeps track of observers that want to be notified
    void registerWeatherObserver(WeatherObserver wo) throws SomeException;
    void removeWeatherObserver(WeatherObserver wo); //A way to unregister people
    void notifyWeatherObservers();// notifies the observers 
}

What design pattern is this? How do you know?

Observer because it implements code that allows for one object to notify multiple observer objects when the state changes.

43
New cards

Define Null Object

provides a default object with empty or default behavior, avoiding the need for repeated null checks in the code.

44
New cards
<p>What design pattern would best fit the image and why?</p>

What design pattern would best fit the image and why?

Monostate because all instances will see and share the same values for the data attributes.

45
New cards
<p>What design pattern would best fit a checkers game where players can undo bad moves?</p>

What design pattern would best fit a checkers game where players can undo bad moves?

Memento design pattern

46
New cards
<p>What design pattern does this image imply?</p>

What design pattern does this image imply?

A flyweight pattern because it shares an instance of the same data that we can retrieve

47
New cards
import java.util.HashMap;
import java.util.Map;


class Price {
    private final String value;  // Immutable

    private Price(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    // Example of an operation
    public Price add(Price anotherPrice) {
        double sum = Double.parseDouble(this.value) + Double.parseDouble(anotherPrice.getValue());
        return PriceFactory.getPrice(String.format("%.2f", sum));  // Use Factory to get Flyweight instance
    }
}


class PriceFactory {
    private static final HashMap<Integer, Price> price = new HashMap<>();

    // Method to get an existing price or create a new one if not found
    public static Price getPrice(int value) {
        if (!prices.containsKey(value)) {
            price p = new Price(value);
            priceMap.put(value, p);
        }
        return price.get(value);
    }
}

public class Example {
    public static void main(String[] args) {
        Price price1 = PriceFactory.getPrice("100.00");
        Price price2 = PriceFactory.getPrice("100.00");
        Price price3 = PriceFactory.getPrice("50.00");

        System.out.println("Price1 == Price2: " + (price1 == price2));  // True, same object reference
        System.out.println("Price1 == Price3: " + (price1 == price3));  // False, different object references

        Price sumPrice = price1.add(price3);
        System.out.println("Sum Price: " + sumPrice.getValue());  // Sum of the two prices
    }
}

What design pattern is this? how do you know?

The Flyweight pattern because it uses a static HashMap in PriceFactory to store and reuse Price objects, minimizing memory usage by sharing instances instead of creating multiple identical objects.

48
New cards
public class USAircraft{
	private USAircraft(){} // 		Static methods, no reason to “new”
	public static Aircraft createAircraft(	String type){
		if (type.equals(“LightTransport”)
			returnnew LightTransportCraft();
		else if (type.equals(“HeavyTransport”)
			return new HeavyTransportCraft();
		else if 	(type.equals(“Troop”))
			return new TroopTransportCraft();
		else if (type.equals(“Fighter”))
			return new FighterCraft();
		else if (type.equals(“Bomber”))
			return new BomberCraft();
		else if (type.equals(“Gunship”))
			return new GunshipCraft();
		else if (type.equals(“Medic”))
			return new MedicHelicopterCraft();
			else return null; // Don’t know what this is…
	}
}

What design pattern is this?

Factory

49
New cards
<p>From this image, what design pattern would help this implementation? and why?</p>

From this image, what design pattern would help this implementation? and why?

The facade pattern because it can create a single class that provides a simple interface to the complex system.

50
New cards


// Main
public class Laboratory { 
	public static void main(String[] args) { 
	System.out.println(); 
	System.out.println("-- Research Laboratory --"); 
	System.out.println(); 
	
	Employee investigator01 = new PrincipleInvestigator(); 
	investigator01 = new SafetyCaptain(investigator01); 
	System.out.println(investigator01.getTitle() + 
	"\n\tResponsibilities include " investigator01.getResponsibility()); 
	
	Employee investigator02 = new PrincipleInvestigator(); 
	investigator02 = new SafetyCaptain(investigator02); 
	**investigator02 = new BloodDriveCanvasser(investigator02);** 
	System.out.println(investigator02.getTitle() + 
	"\n\tResponsibilities include " + investigator02.getResponsibility()); 

	Employee technician = new ResearchTechnician(); 
	**technician = new ComputerSecurityOfficer(technician);** 
	technician = new BloodDriveCanvasser(technician); 
	System.out.println(technician.getTitle() + 
	"\n\tResponsibilities include " + technician.getResponsibility()); 

	Employee admin = new AdministrativeAssistant(); 
	admin = new BloodDriveCanvasser(admin); 
	System.out.println(admin.getTitle() + 
	"\n\tResponsibilities include " + admin.getResponsibility()); 
	} 

}
//usage 
Employee technician = new ResearchTechnician();
technician = new SafetyCaptain(technician);
System.out.println(technician.getTitle());  // Outputs: Research Technician, Safety Captain

What design pattern does this main imply? and how do you know?

Decorator because the calls are wrapping around an interface or implementation in order to dynamically change its behavior

51
New cards
<p>What UML design pattern is this?</p>

What UML design pattern is this?

Composite design pattern

52
New cards
public interface PackageComponent {
    double getWeight();
    String getId();
    void addPackage(PackageComponent pc) throws Exception;
    PackageComponent getPackage(String id);
    int getPackageCount();
}
public class Package implements PackageComponent {
    private String identifier;
    private double weight;

    public Package(String id, double w) {
        this.identifier = id;
        this.weight = w;
    }

    public double getWeight() {
        return weight;
    }

    public String getId() {
        return identifier;
    }

    public void addPackage(PackageComponent pc) throws Exception {
        throw new Exception("A Package cannot have Packages added to it!");
    }

    public PackageComponent getPackage(String id) {
        return null;
    }

    public int getPackageCount() {
        return 1; // A single package
    }
}
public class ShippingContainer implements PackageComponent {
    private String identifier;
    private HashMap<String, PackageComponent> items = new HashMap<String, PackageComponent>();

    public ShippingContainer(String id) {
        this.identifier = id;
    }

    public double getWeight() {
        double totalWeight = 0;
        for (PackageComponent pc: items.values()) {
            totalWeight += pc.getWeight();
        }
        return totalWeight;
    }

    public String getId() {
        return identifier;
    }

    public void addPackage(PackageComponent p) {
        items.put(p.getId(), p);
    }

    public PackageComponent getPackage(String id) {
        if (items.containsKey(id)) {
            return items.get(id);
        }

        for (PackageComponent pc : items.values()) {
            PackageComponent found = pc.getPackage(id);
            if (found != null) return found;
        }

        return null;
    }

    public int getPackageCount() {
        int totalCount = 0;
        for (PackageComponent pc : items.values()) {
            totalCount += pc.getPackageCount();
        }
        return totalCount;
    }
}
public class Ship {
    private HashMap<String, PackageComponent> cargo = new HashMap<>();

    public double getWeight() {
        double totalWeight = 0;
        for (PackageComponent pc : cargo.values()) {
            totalWeight += pc.getWeight();
        }
        return totalWeight;
    }

    public void addPackage(PackageComponent p) {
        cargo.put(p.getId(), p);
    }

    public PackageComponent getPackage(String id) {
        if (cargo.containsKey(id)) {
            return cargo.get(id);
        }

        for (PackageComponent pc : cargo.values()) {
            PackageComponent found = pc.getPackage(id);
            if (found != null) return found;
        }

        return null;
    }

    public int getPackageCount() {
        int totalCount = 0;
        for (PackageComponent pc : cargo.values()) {
            totalCount += pc.getPackageCount();
        }
        return totalCount;
    }
}

What design pattern is this? And how do you know?

This is a Composite pattern because it allows both individual items (packages) and groups of items (containers) to be treated the same way through a shared interface, PackageComponent.

53
New cards

What design pattern is this? and how do you know?

```java
public class EnvironmentMgr {

    _// Static attributes shared across all instances_

    private static double temperature;
    private static double humidity;

    _// Accessor methods_
    public double getTemperature() {
        return temperature;
    }
    public void setTemperature(double temperatureIn) {
        temperature = temperatureIn;
    }
    public double getHumidity() {
        return humidity;
    }
    public void setHumidity(double humidityIn) {
        humidity = humidityIn;
    }
}

Monostate because it uses a static reference, but looks like a singleton.

54
New cards

Whats the difference between Monostate and Singleton?

The Singleton pattern ensures only one instance of a class exists, while the Monostate pattern allows multiple instances but ensures they all share the same state by having static data members.

55
New cards

Define the flyweight design pattern

optimizes memory by minimizing the number of duplicate objects by sharing one object among all instances requiring the same state.

56
New cards

What other design pattern does the flyweight pattern use?

Factory

57
New cards

How is the Factory design pattern used in the flyweight design pattern?

it’s used to manage object creation, ensuring that no duplicate objects are created. If a requested object already exists, the Factory returns a reference to the existing object instead of creating a new one.

58
New cards

True or False. Flyweight objects are immutable

True

59
New cards
<p>What design pattern is this?</p>

What design pattern is this?

Decorator

60
New cards

Define Liskov Substitution Principle

If a program uses a base class, it should be able to use any derived class without the program breaking. This ensures inheritance is used correctly.

61
New cards

Whats the difference between comparable and compareTo?

Comparable is an interface, while compareTo is a method within that interface that compares the current object with another object to determine its relative order.

62
New cards

Define Association Composition

offers greater FLEXIBILITY because the relationships among the visible parts can be redefined at run-time.

63
New cards

Define Aggregation Composition

allows for greater SECURITY because its structure is defined in advance, and cannot be altered at run-time.

64
New cards

Define Information Hiding

when we hide the details of the design, algorithms, and data structures that may change over time and expose methods that won't change

65
New cards

Define Abstraction

a model that contains the most important aspects of something.

66
New cards

Why is abstraction important?

Because it can simplify a complex situation based on the real world

67
New cards

Which design patterns are often seen in addition to the Facade pattern?

A) Strategy

B) Data Transfer Object

C) Singleton

D) Factory

B and D

68
New cards

Which design patterns are often seen in addition to the Strategy Pattern?

A) Null Object

B) Data Transfer Object

C) Singleton

D) Factory

A and D

69
New cards

Which design patterns are often seen in addition to the Data Transfer Object pattern?

A) Facade

B) Factory

C) Strategy

D) Null Object

A

70
New cards

Singleton

Ensures that a class can only have one instance and provides a global access point to the one instance.

71
New cards

Facade

Specifies the creation of a class with a simple interface to a complex subsystem or complex set of entities, decoupling the subsystem from client classes and other subsystems.

72
New cards

Dependency Inversion Principle

Specifies that you should code to an interface, not to an implementation.

73
New cards

Strategy

Allows multiple implementation classes to be created when a variety of algorithms are needed to handle interface behaviors.

74
New cards

Open-Closed Principle

Indicates that when requirements change, you can extend the behavior of such modules by adding new code, not by changing old code that already works.

75
New cards

Data Transfer Object

Often used in conjunction with the "Facade" pattern to encapsulate only key certain data elements of a domain object in a simple class.

76
New cards

Single Responsibility Principle

There should never be more than one reason for a class to change.

77
New cards

Encapsulation

Principle which states that data members, and the methods that operate on that data, must exist in the same class.

78
New cards

Inheritance

Defines a technique in which a class can inherit characteristics and features from more than one superclass.

79
New cards

Factory

Insulates client code from the details of object creation by having clients request the creation of an object, and results in an appropriate object being created and returned to the caller

80
New cards

Polymorphism

The idea of allowing the same code to be used with different types of related objects, resulting in more general and abstract implementations.

81
New cards

Static

Indicates that the data attribute or method is "owned" by the class, not by objects (instances of the class).

82
New cards

Separation

Specifies that the "interface" to a class or subsystem must be distinct and decoupled from the "implementation" of that class or subsystem.

83
New cards

Composition relationships generally fall into categories: aggregations and associations.

Which is true about these 2 composition types? (Circle all that apply). (3 pts)

a) In an aggregation relationship, the "parts" are visible and accessible. b)

b) In an aggregation relationship, the "parts" are not visible or accessible.

c) In an association relationship, the "parts" are not visible or accessible.

d) In an association relationship, the "parts" are visible and accessible.

e) None of these are correct.

B and D

84
New cards

True or False:

A class acting as a Factory that creates different types of objects that implement the same interface cannot return the objects using the interface type.

False

85
New cards

True or False:

The Singleton design pattern ensures that only one object of a class. This is managed within the class by implementing a static counter that will have the value 0 (no object yet created) or 1 (the single object has been created).

False

86
New cards

Identify the Design Pattern or Patterns present in the following java code and explain why. (Check all that apply).

public final class Environment {

    private static Environment instance;

    // Private constructor to prevent instantiation
    private Environment() {}

    // Method to get the singleton instance
    public static Environment getInstance() {
        if (instance == null) {
            instance = new Environment();
        }
        return instance;
    }

    // Method to get temperature at coordinates (x, y)
    public double getTemperature(int x, int y) {
        // Complex weather-resource code goes in here
        return 0.0; // Placeholder return
    }

    // Method to get humidity at coordinates (x, y)
    public double getHumidity(int x, int y) {
        // Complex weather-resource code goes in here
        return 0.0; // Placeholder return
    }
}

A) Singleton

B) Data Transfer Object

C) Facade

D) Factory

E) Strategy

F) Null Object

G) None of these

H) All of these

Singleton and Facade because it uses one instance of Environment, and the Facade pattern because it provides simplified methods (getTemperature and getHumidity) to access complex functionality.

87
New cards

Identify the Design Patterns or Patterns present in the following java code and explain why. (Check all that apply)

public class CalcMaker {

	if (style. equals ("BASIC")) {

		return BasicCalculator (metric);

	}else if (style.equals("SCIENTIFIC")){

		return ScientificCalculator (metric);

	}else {

		return DefaultCalculator (metric);

A) Singleton

B) Data Transfer Object

C) Facade

D) Factory

E) Strategy

F) Null Object

G) None of these

H) All of these

Its Factory because It creates different types of calculators (BasicCalculator, ScientificCalculator, DefaultCalculator) based on the given style, and its Facade because It provides a unified interface (CalcMaker) to create calculators, simplifying access to different calculator types by hiding the complexity of their instantiation.

88
New cards
public class CustomerData {

	public String customerId;

	public String lastName;

	public String firstName;

	public double avgPurchase;

	public int purchaseCount;
	
	public CustomerData(String ci,String In,String fn, double ap, int pc) {

		customerId = ci;

		lastName = rn;

		firstName = fn;

		avgPurchase = ap;

		purchaseCount = pc;

	}

}

What design pattern is shown in the code?

A) Singleton

B) Data Transfer Object

C) Facade

D) Factory

E) Strategy

F) Null Object

G) None of these

H) All of these

B

Data Transfer Object

89
New cards

Does this refer to inheritance or Interface?

“Used to define a “Role” and the behaviors that role requires”

Interface

90
New cards

Does this refer to inheritance or Interface?

Best used to encapsulate structural commonalities

Inheritance

91
New cards

Does this refer to inheritance or Interface?

Can only include constant (final) data members.

Interface

92
New cards

Does this refer to inheritance or Interface?

Defines a parent-child relationship.

Inheritance

93
New cards

Does this refer to inheritance or Interface?

Allows you build a new class based on an existing class's implementation.'

Inheritance

94
New cards

Does this refer to inheritance or Interface?

Best used to encapsulate behavioral commonalities.

Interface

95
New cards

Does this refer to inheritance or Interface?

Involves extension by other classes.

Inheritance

96
New cards

Does this refer to inheritance or Interface?

Couples two classes together.

Inheritance

97
New cards

Does this refer to inheritance or Interface?

Used with the Strategy design pattern.

Interface

98
New cards

Does this refer to inheritance or interface?

Used in conjunction with Delegation

Interface

99
New cards

Does this refer to inheritance or Interface?

Involves implementation by other classes.

Interface

100
New cards

Does this refer to inheritance or Interface?

Can include methods with public, private, protected, or package visibility.

Inheritance