Q and A
How to come up with object oriented design solutions
The typical OOD question used to test your object oriented programming skills with a real solution will give you a vague problem like:
• Design a game of blackjack
• Design an URL shortener service
• Design an ATM
• Design a two-player chess game
• Design a restaurant
• Design a parking lot
• Design an online stock brokerage
The problem may also have some constraints to give you a better idea of the solution the interviewer expects. For example, you could limit the blackjack game to a dealer and one player. Pay attention to these constraints because they will keep you from overthinking your solution and spending a lot of time building a solution that doesn’t fit the problem. I’ve authored a top-rated object oriented design course covering the SOLID principles of object oriented design that can help with this.
Even with some practical constraints, you will still have a lot of work ahead of you. To make this process easier, you can use these steps to narrow down the functionality you need to create:
1. Ask questions. If you don’t completely understand the requirements, ask some questions. I actually encourage you to ask questions to clarify both the interviewer’s and your own assumptions about the problem, so you and the interviewer agree. This will not only show that you are a responsible problem solver but also detail-oriented in your approach to thinking about the requirements.
2. Don’t jump right into writing code. Describe the use cases. Describe to the interviewer how people will use your system. Draw workflows and diagrams, especially if there is a whiteboard or notepad available in the room. Make a list of use cases and say them out loud. Describing and organizing your thought track is actually a very good interviewing technique and shows confidence in your ability to break down problems. This will all help you better determine the functionality your system will need at the outset instead of halfway through your solution when change is harder to pull off.
3. Identify the objects and their relationships with each other at a high-level. For example, in the blackjack game, you could create the following objects: deck, card, player, dealer, and game. These objects have relationships with each other, and you should draw them out at a high-level to clarify how they would interact.
4. Describe each object’s attributes and behaviors. Get into more detail about each object’s characteristics/attributes and behavior. Behavior typically relates to methods that would be needed on the object to perform some kind of work.
Object Oriented Programming students also learn
5. Organize relationships and class hierarchies. Here is where you need to get specific about object relationships and how to organize class hierarchies. For example, you may find that the Dealer class should inherit from the parent class Player. But a dealer object would have the specific deal() method or a shuffle() method, whereas the parent class of Player would not.
6. Look for design patterns. Once you know how your objects interact, you can now look for places to apply object oriented design patterns that fit your application’s needs. Don’t be quick about forcing a specific object oriented design pattern to fit with the application. Only apply the pattern if it makes sense. Newcomers often try to force design patterns into their code, and that can make the application more complex than necessary if the pattern does not fit naturally. Watch out for this!
Remember, there is no “right” answer to one of these types of interview questions. The interviewer is simply trying to determine:
• Can the candidate ask the right questions to gather requirements about the problem?
• Can the candidate identify objects and how they interact from the problem?
• Is the candidate comfortable with OOD principles and design patterns?
• How does the candidate balance the need to have software that they can code quickly and software that can adjust to the system’s changes?
Don’t overthink or get nervous, but do make sure you fully understand the problem, and you should do fine. Now let’s look at some general questions a tech interviewer may ask you.
19 popular object oriented interview design questions
Here are some questions that interviewers may ask to test your basic knowledge of object oriented design principles.
1.
What is aa...
-
Class:
- A class is a fundamental building block in
objectobject-oriented programming. - It
theserves as a blueprint for definingan objectobjects inyoursoftware,a class contains thecontaining properties andmethodsmethods. - OOP
isallowsthe ability offor one class to inherit fromanother.another,2.facilitatingWhatcodearereuse.
Consideredthat make your objects function. One advantage ofproperties - A class is a fundamental building block in
-
Properties and
methodsMethods:of- Properties are the
“nouns”attributes (nouns) ofyour classes. They let the programmer define the attributes of the object. For instance, if you haveaclassclass,thatdefiningdefinescharacteristicsa house, the class properties would describe the house’slike color, size,andetc. - Methods are the
“verbs”behaviors (verbs) ofyour class. Another way to think about it is that methods are behaviors your object carries out. For example, if you haveaBirdclass,fly() would be a method. This will allow bird objects to fly. Methods are named blocks of code that contain instructions that are made part of the class’ blueprint that define thedefining actionsthelikeobjectsfly(),ofeat(),thatetc.
a class?materials.classmust - Properties are the
-
out.Inheritance:
3.What is inheritance? - Inheritance allows
onea child class to use thesamemethods and properties ofanother class. A child class “inherits” its methods and properties froma parent class. - Child
sayclassesyouinherithavebehavioranfromAnimalparent classes, facilitating code reuse and promoting a hierarchical structure. - For example, a Bird class
thatmaycontains attributes like weight and size. It can containinherit methods like eat()orand sleep(). A Bird class would naturally inheritfromthea parent Animalclassclass,because a bird is an Animal. Becauseas birds are akindtype ofAnimal,animal.they-
naturallyHierarchy
inherit the behavior of eating and sleeping as defined in the parent Animal class. This is one example of code reuse. You should not need to redefine eat and sleep methods in the child class Bird if bird is an Animal and the Animal class already contains these methods.Building:Empoweryour team. Lead the industry.Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business. - Inheritance allows
youfortothebuildcreation of a hierarchy ofclassesclasses,tomirroringsimulatereal-worldtherelationships. - It simulates how objects
in the real worldrelate to each other through an IS A relationship.
wouldwayThisis -
-
importantUnderstanding
pointISthatAnewcomersRelationship:miss.- The goal of inheritance is not just to
justinheritmethods.methodsIt’sbutabidingtobyadhere to the IS A relationshiprule!rule. - It ensures that subclasses represent specialized versions of their superclass and are related in a meaningful way.
- The goal of inheritance is not just to
-
Avoiding Poor Design:
- Inheritance should not be used indiscriminately for method reuse.
- For example,
both Vehicle and Animal classes could have the move() method defined, butabirdBird class shouldnevernot inheritthefrom a Vehicle classjustsolely to use the move() method.That’sThis violates the IS A relationship principle and leads to poor design.
-
Key Principle:
- The IS A relationship is
keycrucial for forming classhierarchies.hierarchiesAandwell-designedensuringapplication allows for goodproper code reuse where it makes sense. - Well-designed
Whatapplicationsisleveragetheinheritancedifferencetobetweenpromoteprivatecode reuse in a meaningful andpubliclogical manner.
4. - The IS A relationship is
Let’s
-
Public vs. Private Methods/Properties:
- Public methods
orand propertiesinareclasses?accessiblePublicfromandexternal classes, while privatedefine the accessibility of a class’ properties or methods.Privatemethods and properties are onlyaccessed by that enclosing class itself. No external classes have access to private members of a class. If there is an inner nested class, that’s enclosedaccessible within the classcontainingitself. - Private members cannot be inherited by child
classes!classes. - Inner
methodsnestedandclassespropertieswithinaretheavailablesame class definition have access tootherprivateclassesmembers.
private members. Then that inner nested class has access to those private members because it is still enclosed within that same class definition. Remember that privatePublictouse. - Public methods
-
Class Constructor:
5.What is a class constructor? - A constructor is
thea method usedwhen youto instantiate an instance of a class. - It
mosttypicallyobject oriented languages, the class constructor will havehas the same name as theclass.classInandmanyinitializeslanguages,specificyouproperties. - Overloaded
haveconstructorsmoreallowthanforonemultiple constructorper class. You can have several overloaded constructors or a constructordefinitions withnodifferent parameters. -
toOverloaded
initialize specific properties in your class.Methods:6.What are overloaded methods? - Overloaded methods
usehave the samemethodname but a different set of parameters. - The order of
theparameters matters, and parameters must have different data typesdoestomatter.avoidIfcompilationtwoerrors. -
sameAbstract
name have the same parameter list data types, but the parameter order is different, that is legal code, and it will compile just fine in Java.Class:7.What is an abstract class? - An abstract class cannot be
instantiated,instantiated butitcan be inherited. - It
means that your inherited class can inherit methods from the parent abstract class, but it cannot directly call the abstract class. Abstract classes are excellent for defining global definitions for your inherited classes, so you only need to create these definitions once. The child class is expected to implement thecontains abstract methodsdefinedthatin the parent abstract class. As a follow-up, you will probablymust beaskedimplementedaboutbyabstractitsmethods.childAnclasses. - Abstract
methodmethodsis a method that isare declared withoutanimplementation(without bracesandfollowed by a semicolon). If a class includes abstract methods, then the class itselfmust bedeclaredimplementedabstract.by subclasses. -
Instantiation:
8.What is instantiation? - Instantiation
isreferswhattohappensthewhencreation of an instance (object) of aclassclass. - It
created.occursAn instance is another term for an object of that class. Callingwhen the class constructor methodinstantiatesisthecalled,object. You cannot use a class before you instantiate it. When instantiated,providing the objecthas thewith properties and methods defined initstheclass’class blueprint. -
Passing Parameters:
9.- Passing parameters by value
andallowspassing them by reference?
What is the difference between passingWhen parameters passmethods toaaccessmethod by value,only themethod only has access to the parameter’parameter'svalue andvalue, not the variableuseditself. - Passing parameters by value
- Passing parameters by reference passes a pointer to the
parameter.variable,Ifallowingthismethodsvaluetois changed when the method executes, it does not affectmodify the original variable. -
Method Overriding:
When- Method
passoverridingbyoccursreference,when apointersubclassactually passes into the method. The pointer references the variable used as the parameter. If the method then modifies this parameter, it will alter the original variable as well.10. What does it mean to override a method?When you create a class that inherits from another class, you can override the parent class’ methods. For example, if the parent Animal class contains the method move(), a child class such as Bird can either inherit the move() functionality from the parent or override it to something more specific to birds. If overriding is done, then the bird will haveprovides its own implementation forthe move()a methodininheriteditsfromownaclasssuperclass. - It
thanallowsinheritingfor customizing theparentbehaviorclassofAnimal’sinheritedgenericmethodsmoveinbehavior.child classes.
parametersrather - Method
-
Exception Handling:
11.What is exception handling? - Exception handling is a process used to
trap thehandle errors thatcanoccurwhenduringyourprogramapplicationexecution. - It allows
usersfortogracefulcontinueerrorusinghandling,the software and gracefully handle issues rather than lettingpreventing the applicationcrash.fromForcrashingexample,andyourprovidingbrowserusersapplicationwithdoesn’tfeedbackcrashonif you lose connectivityhow totheproceed. -
says"this"
“retry connecting” or something similar. This is an example of exception handling done correctly in the software. Exception handling is done to capture error scenarios that are outside of the developer’s control.Object:12.What is the “this” object? - The
“this”"this" reference refers to the current instance of theobject.objectYouwithintypicallyauseclass. - It is used to
referenceaccessaninstanceinternalvariablespropertyandormethodsmethod ofwithin the class. -
“this”Pointer:
in- Pointers
programming languages. Python uses “self” instead of “this,” butreference theconcept is the same.13. What is a pointer?Pointers are typically used by name in C++, but they also apply in other programming languages. Pointers “point” to the actualmemory location of avalue. Because a pointer references the actual value, when you change avalue inaprogrammingpointer,languagesyoulikechangeC++. - They allow for direct manipulation of memory values, affecting the
valueoriginalindata.
manymemory. - Pointers
-
Static Methods:
14.What are static methods?The static keyword defines - Static methods
that willexist independently ofanyclass instancescreated from the class. Static methodsand do not have access toany of theinstancevariablesvariables. - They are
beneficialusefulwhenforyoudefiningneed quick execution ofutility functions thatdon’tdoneednototherrequirepartsaccessoftotheinstance-specificcontainingdata.