OOP_Java Flashcards
What must we know about Java before fully being able to implement OOP in Java?
Know Java basics!
This course has intermediate topics!

What are the styles of programming used in computer science?
Object-oriented and functional are the two most popular used today!

What are programming paradigms?
They are styles of writing code.
OOP, Procedural, Functional
Many languages support multiple paradigms.
Not languages!
Ex. Python, Ruby, Java, Javascript

Which programming languages support multiple programming paradigms?
OOP, Procedural, Functional:
Python, Ruby, Javascript, Java

What is everything based on in object-oriented programming (OOP)?
Everything is based on the concept of objects
The objects are units that contain:
data
methods (behaviors) that act on the data

What is the challenge with OOP?
It’s fairly complex.
Many books fail to explain it properly.
What is an object?
Units that contain:
data (state)
operations on data (behavior) - methods/functions
Together in a single unit
Describe functional programming
vs. OOP?
Functional:
Data (fields)
Behavior (methods/functions)
*Completely independent of each other
OOP:
Data (fields)
Behavior (methods/functions)
*Grouped together in Units
Which style of programming is the best?
It depends on the type of problem you are trying to solve!
Some paradigms make more sense in a given context
No paradigm works best in all situations.
Every problem is different.
It all depends on the problem, context, budget
Ex.
Some make the mistake to try to solve all problems in one style or way of programming (OOP vs. functional).
What is a problem in the software industry?
Engineers are more excited about new languages and features than actually solving problems.
They think they know how to solve problems when actually they don’t!
What is problem-solving?
The definition of engineering problem-solving.

When is Object-Oriented Programming a better choice?
Graphical user interfaces and games!
When is functional programming a best choice?
In applications that require a high amount of reliability.
Problems that involved messages that get passed around and transformed along the way.
When might our application use different paradigms in a single application?
the event-driven paradigm in parts that make sense
functional or object-oriented paradigm parts that make sense.

Is there a one-size-fits-all for software engineering?
No!
Every problem is different.
depends on the project, the context, and the budget!
What is object-oriented programming?
A programing paradigm that groups data and methods that act on the data together in objects.
Object-oriented programming is about objects.
These objects interact with each other to perform various tasks!
Ex.
A car consists of thousands of collaborating objects that are reusable and replaceable!
What are the benefits of OOP?
Ex.
We can break a large application into smaller parts, we can focus on code for that object.
Fix the object or plugin another object.

What is covered in this course?
Classes - building blocks of OOP
What they are, how to build them
Encapsulation
Abstraction
Refactor Mortgage calculator to OOP
Inheritance & Polymorphism
Interfaces - coupling problems
JDK classes + frameworks

What is the most important section of this course?
The exercise of refactoring code into OOP format is a crucial skill all Java developers must have!
hardcore coding techniques NOT found in any other courses.
Taking procedural code and refactoring into OOP

What does refactoring procedural code into OOP look like?
Procedural:
A bunch of methods calling each other in one main class!
OOP:
Use abstraction
Use encapsulation
Use inheritance
What is covered on classes in Java?
Encapsulation
Abstraction
Constructors
Getters/Setters
Method Overloading
*Many of these concepts are misunderstood by developers

What is a class?
A template or blueprint for creating objects.
The fields are variables storing data
The methods act on the data values

What is an object?
An instance of a class
independent of each other.
Stored in separate memory locations
Can be in its own state
Ex.
Current speed vs. Current Gear
different in each car object

What is UML?
A simple visual language we use to show classes and their relationships
Unified modeling language
visualize classes

What is the difference between a class and an object?
A class is a blueprint or template for creating objects
Objects are an instance of a class but are independent of each other.

What is a real-world example of a class?
UML
Textbook class

When do we use Pascal naming convention?
Classes

When do we use camel case notation?
Methods in a class

When do we use the .this keyword?
When we want to set the value of the object’s field to the value of the parameter that is passed into the method.
Ex.
this.text = text;
**sets current object text field to the value of the parameter text
Our object has a field text
Our method passes in a parameter called text
we want to set the text passed into our setText method
as the value of the text field in our object

How do we implement the TextBox class in Java?

What are reference types by default?
Null
This can cause our program to crash

Why do we instantiate a new object using the “var” keyword in Java?
The “var” keyword in Java
The Java compiler will detect the type based on what’s on the right side w/ the new operator!
We can reduce the redundent type declaration
In Javascript var is for variable!

What is the most popular exceptions in java?
null pointer exception
Happens when
we try calling methods on an object that is null (field exist)

Are two objects equal?

No.
They can be in different states.
They can have different field values.

How does Java manage primitive and reference variables in memory?
Heap
stores objects + fields
Stack
stores primitives
variables that store references to objects (heap addresses)

How does memory de-allocation work in Java?
When we exit a method
all variables stored on the stack
immediately removed
leaving an object on the heap w/ no reference in the stack
after some time, objects in heap, not reference are erased
Garbage collector = removes unused objects on heap
What is encapsulation?
Inside a single “unit” or “object”

What is a example of proceduring programming?
Data
Functions that operate on the data
long parameters for functions
a fat main. file
technically this example is okay because length of code and simple one method
as programs get longer, more complex
it becomes difficult to separate the different functions and their values
because each function isn’t encapsulated in a main class
changing an object
a change in one function may break the implementation of

What’s the challenge with procedural programming?
With this style of programming we will end up with a bloated or fat main class
You end up with methods that have so many parameters
What are “getters/setters” ?
Common methods in Java
Used to get or set the value of a field!
Implemented in the class.

How do we create a new class?
Right Click src folder
Pascal Notation

What does setting a variable to a reference type mean?
Means you are referencing the same object in memory

What does this code demonstrate?

Object-Oriented Programming
Textbox class is instantiated into TextBox Objects

Is using classes and objects writing code using Object Oriented code (OOP)?
No.
Object-oriented programming is way more than using classes and objects
Going to show the techniques in this course
What is spaghetti code?
Programs with fat main classes
soon as you change something, other things break
so many functions all over the place
to re-use functions have to copy code from here/there but arguments and parameters differ
everything is interconnected!
What does encapsulation mean?

First principle of OOP:
bundle data + methods that operate on data
=
in a single unit (object)

When do we use the static keyword in declaring a method?

Only when we want to call a method from the main class.
Why don’t we need to add parameters to this method?

We are storing these inside these fields in this class already
A sign of OOP is methods without parameters

How can we refactor this code to object-oriented design?

Main classes is cleaner
encapsulated data + methods that act on data

Where should we put data validation logic?
Encapsulate the logic in our Class
What are exceptions?
Classes in Java Library
That exception, if not handled will terminate our program

How can we encapsulate the logic for data validation in our program?

How can we prevent an object from going into an invalid state?
use setters to handle error handling and data validation
encapsulate the logic in the object
What do we want to do with our fields in java?
set them to private
use getter/setter methods to work with them

How can we modify access to our fields?
Set them to private fields in a class
create getter/setter methods for accessing these private fields
IntelliJ light bulb automatically builds getter/setters

What is abstraction?
The second principle of OOP:
Why?
Reduce complexity
Hide implementation details of a class
hide unnecessary details in our classes
Treat it like a black box
What is a real-world example of abstraction?
TV remote:
Remote control w/ buttons
inside electronics/transistors (complex)
all we want to do is change the channel
don’t care about the states
What is the idea behind abstraction?
Hide implementation details
expose a number of methods for others to use!

What is coupling?
The level of dependency between classes
An extremely important concept in OOP
Many developers don’t understand this

What do we want to reduce?
The level of coupling between classes
no such thing as zero coupling
all classes are working together
What’s the problem with coupling?
The more our classes are coupled, the more costly a change in a single class has on the entire class ecosystem
Reducing coupling, reducing impact of changes
What situation do we try to avoid?
Having an application with a thousand tightly coupled classes
Make one change to a class and cause other dependent classes to stop functioning

What is the benefit of reducing coupling?
Reducing coupling, reducing impact of changes
What’s a best practice for reducing coupling?
Making methods private.
Better to hide or delete methods
The more methods a class provides, the more other classes are going to get coupled to it
Each accessible method is a coupling point
What’s the main idea behind abstraction and reducing class coupling?
Reduce the number of methods exposed outside of a class

Reduces coupling
Reduces complexity
What is an IntelliJ shortcut for creating a new method?
Write the method name and give it a parameter name
Click lightbulb to generate a method

What is a good IntelliJ shortcut?
Option + Enter
Opens lightbulb for creating methods and fields

What is Object-Oriented Programming not?
Creating classes with fields and methods only!
OOP has a number of techniques
It’s not about features only - fields and methods
It’s a way of thinking
Encapsulation - grouping fields and methods
Abstraction - hiding implementation details
What do we want to do with our class interfaces?
Make the interfaces as simple as possible
This is the principle of abstraction in OOP
How can we avoid instantiating an object in an invalid state?
Set the initial values to a valid state
This is a constructor function’s role
What is the general convention for organizing members in a class?
Public Fields
Private Fields
Constructors
Public Methods
Private Methods
Getters/Setters
What is a constructor?
A special method that is called when we instantiate an object
Used to create a new object
What is the role of the constructor?
initialize our fields to their default values
Num = 0;
boolean = false
reference type = null;
If we don’t create a custom constructor, what will Java do?
Java compiler will initialize a custom constructor for us
default constructor
all values set to default values!
How can we create a custom constructor?
Under the field declarations
declare a new method using the exact PascalCase name of the class
Ex.
call setBaseSalary and pass arguments
this setBaseSalary has data validation logic
Therefore we’ll never be able to set our object field to invalid states!

What is this an example of?
Object-oriented programming
Abstraction and encapsulation
Class only has one accessible method
The interface is very simple and clean
What is method overloading?
A different implementation of a method with different parameters
implementations of a method with different paraments
What will make our applications hard to maintain?
Overloading a method too many times
So many different implementations
When is it best to overload a method?
Dealing with completely different parameters
Ex.
One takes an integer, one could take an object
Completely different parameters!
What is constructor overloading?
Technically, constructors are methods!
What is one way to overload a constructor?
Pass zero in for a parameter
Duplicate the constructor code
change parameters for the function
initialize one of the fields to zero value

What is another method for overloading a constructor?
Use .this operator to call the constructor function
Can call the constructor
Why?
Reuse logic in the constructor method

What is an IntelliJ shortcut for looking at the parameters of a method?
Command + p
What is an IntelliJ shortcut for duplicating code?
command + d
What is the IntelliJ shortcut for jumping to a method declaration?
Command + b
What are instance members?
Fields or methods that belong to each instance of a class (object)
Accessible with the .dot operator
What are static members?
Fields and methods that belong to a class

How do we access static members?
Directly through the class
We don’t need to instantiate an object
Ex.
Employee class .dot operator accessible
employee .field object not required

When do we use static fields?
When a value is independent of objects
Want to share it across all objects
Ex.
numberOfEmployees in Employee class
What is important to note about static methods?
They can only access other static methods and fields in the class
cannot access instance methods
Must create an object to access the instance methods

What is an example of static members?
Many classes in Java have static libraries
Ex.
Integer.parseInt ( )
this is a static method in the Integer class
What classes do we need in our application?
Think of responsibilities or concerns
Each class has a single responsibility!
Ex. Restaurant
Chef, waiter, waitress
All objects collaborate to create a service
How many responsibilities should each class have?
One
Single - responsibility principle
What is the intelliJ shortcut for refactoring?
Control + T
Refactor:
Move, Rename, etc.

What is the incorrect way to refactor code into OOP?
Cut and paste into a new class
Causes methods to break
Use IntelliJ (Option + T)
What is the best method for refactoring this code?

IntelliJ (Option + T)
Creates a new Class
Moves the implementation to clas!s

What is safe refactoring?
Instead of manually moving code around
Use IntelliJ
Refactor w/ Control + T
Why?
Faster, produces fewer errors!
How can we move two methods into a new class?
IntelliJ Control + T

Select both methods!
What is an IntelliJ shortcut for generating code for constructors?

Command + n
Generate getter, setter, constructor!

How can we refactor this code?

Change signature
parameters are now fields encapsulated in the class
remove them w/ IntelliJ

How can we find breaking changes?
Hover cursor over class name
right click

Have often should we use static methods and fields?
Not that often!
They’re troublesome
What is an IntelliJ shortcut for refactoring a static method into an instance method?
Control + T
Convert to an instance method

What is an example of encapsulation in action?
Store parameter values in fields of the class
Having some state
Having some
How do we initialize our private fields?
Using a constructor!
Remove parameters in signatures by creating private fields to store their values in the class
Set the parameter values to the objects fields

How can we create a getter using IntelliJ?
Click the red light bulb
Read-only getter
How do we refactor code for calculating monthly interest and number of payments in our mortgage calculator class?

Control + T
Extract both expressions into private getter methods
Abstract:
getMonthlyInterest
getNumberOfPayments

What is the IntelliJ shortcut for moving lines of code down a class?
Option + Shift + Down Arrow (Up Arrow)
As a best practice, where should our getters and setters be in our class?
At the bottom of the methods

How can we extract and refactor displaying remaining balance in our MortgageReport class?
Calculate balance and store in an array in CalculatorMortgage class
Iterate over array using a foreach loop to display

How can we refactor this inline variable code?

Control + T
Inline variable

What is included in the Inheritance section?
Important concepts:
Constructors - base class vs. child class
Access modifiers - accessing private base class fields
Overriding methods - changing child method behavior
Comparing objects - creating equal methods to compare objects
Polymorphism -

How can we refactor our currency object in our MortgageReport class?

Refactor -> Extract -> field
initialize in a constructor

What is inheritance?
Re-use code
Define all behavior in a single class
Have other classes inherit behaviors

What is a real-world example of inheritance?
Graphical User Interface:
Textbox, drop-down list, radio buttons
Objects share common behavior!
enable or disable
setSize
Re-use code!
Define common behavior in a single class (UI Control)
Have other classes re-use code!

How can we implement a UIControl superclass?
Give it some members
isEnabled
disable / enable

How can we have a class inherit all the features we defined in a superclass?
add “extends + SuperClass name”
Now objects can access methods from Superclass!

What members did our TextBox class inherit?

TextBox Members:
clear ( ), setText ( )
UIControl Members (Inherited):
disable ( ) , isEnabled ( ) , enable ( )

What is the object class?
Additional methods all objects have
Object class in Java.Lang package inheritance
What does Java Compiler automatically do for us?
Adds the extends Object to our classes
All Java Classes Inherit from the Object class!

What are the members in the java base Object class?
getClass - returns class objects (read meta data about object)
equals - comparing objects
hashcode - integer based on location
toString - returns string of object
notify - concurrency
notifyall - concurrency

What is the hash method in the Object base class?
Returns hash of the object reference in memory!

What does the base Object class’ equals method compare?
Compares two objects based on the hash code!
Not the coordinates or values!
We can override this method to compare values!

What does the base Object class’ toString method return?
Returns string representation of an object
Has two parts:
1. fully qualified name of class (package)
2. hashcode represented as hexidecimal
There are situations where we can override!
To return values in an object instead!

How do constructors work given inheritance?

First, the constructor of the base class is called
Then, the constructor of the sub-class

What if our base class has a parameter in the constructor?

We must explicitly call the base class constructor
as the first statement in our child class constructor!

If our base class constructor has a parameter, how do we pass a value in our subclass?

In our subclass constructor
Call the “super” keyword to call the base constructor
pass a value to the parameter here

Are private members inherited by subclasses?
No, they are not inherited by subclasses.
Private fields/methods are not inherited!
Not accessible outside the class!
Private members are used to hide implementation details
What is the protected keyword?

It sets fields to public inside the package
We can access the field only inside the package!
Treated like a bad practice/code smell!
Avoid it!
Hard to maintain applications!
Use public and private!

What is the default access modifier?
Package private
public anywhere in the package
private outside the package
classes in other packages cannot inherit
Stay away from this!
Stick with public and private!

What is method overridding?
Inherit a method from base class
want to change implementation
override a method in base class
Not method overloading (changing signatures)
When do we use method overriding?
When we inherit a method from a base class
but aren’t happy with it and want to change its behavior
What is an annotation?
A label we attach to a class member
Gives extra information to the Java compiler
like @override!
Helps compiler double-check code!
Ensure the exact same signatures used!
What is an example of method overriding?

The string method from base class!
Want to override it to display the values NOT the location in memory.

How do we implement method overriding?
After the constructor
@Override annotation!

What is upcasting and downcasting?

What’s an example of upcasting?
textBox (child) is a UI control (base)
Therefore,
TextBox is automatically upcast to UIControl
I.e. we have a method that requires a UI control object but instead pass a child of the UIControl class and it upcasts it and acts on the data type!

When giving a derivative of a base class to a method, how can we access the child class’ methods?
Explicitly cast it
Using a Prefix
Downcasting
When do we use downcasting?
Even though at run time we are passing a child object to its parent’s method, at compile time we don’t have access to the child’s methods.
Must explicitly cast it down

How do we prevent exceptions when casting?
When casting:
General cannot cast to specific
(parent) cannot cast to (child)
specific can cast to general
(child) can cast to (parent)

What will this expression produce?

False.
Why?
Points are reference types, values stored in variables are the address in memory (not values). We have two different point objects, two different values.
The default equal method in the base object compares references (hashes), not values!

What is a shortcut for over-riding methods?
Command + n
Override methods
List of methods!

How can we solve the class cast exception?
Make sure the object passed at runtime is an instanceOf our child class
Ex.
If not instanceOf return false
otherwise, cast it and compare values

How can we manually override the equals method in the Object class?
Check if the object reference is equal (this)
Check if instanceOf
cast and compare values!

What is the best practice for overriding the equals method?

Override the hash method also!
Hash generated based on values in object NOT location in memory

What is an IntelliJ shortcut for overriding the equals and hash methods?

Command + n
(generate menu)
Select equals ( ) and hash ( )

What is polymorphism?
The fourth principle in OOP:
“Many forms”
Allows an object to take different forms

Where can we use polymorphism?
Rendering an object in different ways
W/o polymorphism we must use a long if statement
will have to modify if statement, etc.

How does polymorphism work?

Define render ( ) in parent class
each child class has its own algorithm (override) for
render ( )
ie. Override each subclasses method
call render and objects behave differently

What is polymorphism in action?
Each object has it’s own implementation of the render ( ) method
When we iterate over the array of different objects, the render method is taking different forms!

When do we use abstract classes?
We declare a class
We don’t want to instantiate it or create a new object
Example.
UIControl is an abstract concept
provides common code for subclasses
How can we declare a class as abstract?
Add the abstract keyword
When to use?
When we want common code for subclasses
But don’t want the parent class instantiated
Example.
UIControl is abstract class
TextBox, CheckBox inherit members!

How can we implement an abstract method?
use abstract keyword
remove curly braces

What do abstract methods force subclasses to do?
Implement the abstract method!

What is a final class?
Prevents other classes from extending!
Cannot inherit from a final class
Want to prevent other classes from extending
We don’t use these often!
Prevents inheritance, polymorphism, etc.
Ex. String class in Java
Immutable, cannot extend this class

What is a final method?
When we declare a method as final, we cannot override it
Used when subclasses accidentally break assumptions or change behavior

What should we not create?
Deep inheritance hierarchies!
People new to inheritance, make this mistake!

What is the problem here?

Deep inheritance hierarchies are tightly coupled
Any changes made to parent, have to modify child classes

How many inheritance levels should we have?
One or two levels!
No more than three levels!
Avoid deep inheritance.
What is multiple inheritances?
In C++ and Python
A class can have multiple parents!
This bring complexities and ambiguities.
Which class to inherit from.
What is the diamond problem?
Which method should D inherit?
You are not going to need it.
Java doesn’t support it!

What are interfaces?
One of the most powerful, least understood concepts of Object-Oriented Programming.
What is covered in this section on interfaces?
What interfaces are
Why we need them
How to use them properly
Dependency injection

What are one of the most misunderstood features of Java?
Interfaces
Why?
A lot of people don’t understand the purpose, the meaning has changed since Java v8
What do we use interfaces to build?
Loosely coupled, testable applications
Why?
Allows us to not directly couple classes

What is an interface really?
A type similar to a class
Only includes method declarations
Includes no code
only defines capabilities
Allows decoupling!
How do interfaces work?
Put an interface between classes to decouple them
Interface only includes method declarations
Programming against interfaces:
Code our classes to work with interfaces
Loosely coupled applications
Makes extending applications easy

How do we name interfaces?
-able suffix
Ex.
Drag able
What do interfaces define and what to classes define?
Interfaces are about “what”
Classes are about “how”
Classes will implement the algorithms or the “how”

How can we create a new interface?
Right click -> interface

What doesn’t an interface have?
Unnessary public keyword - all methods must be access outside class
no fields, no state, no data!

How do we use an interface?
use the implements keyword in the class declaration

As a best practice, what should we apply to our interface methods?
The @override annotation!

What is dependency injection?
Principle:
Says creating an object and using an object are different concerns
We should separate these concerns!
Take responsibility for creating dependency and put it into another class
Other class will inject a dependency via:
Constructor injection
setter injection
method injection

What is called poor man’s dependency injection?
Creating and injecting dependencies by hand
In a real application may have hundreds of objects
Don’t want to create and pass them all to constructors!
Use dependency injection frameworks for this.
“Spring” is one approach.

What is dependency injection using a constructor?

It’s the responsibility of our main class to pass a concrete object to the TaxReport class.
The TaxReport class only implements an interface!
Most common injection approach!

What is dependency injection using setters?
Creating a method to inject dependency
Why?
Allows us to change the dependency through the lifetime of our application

What is the benefit of using setter injection for our dependencies?

We can change the dependencies of a class throughout the lifetime of the application.
But we have to remember to call it!
Can pass a new instance of a class that implements the interface!

What is method injection?

Pass the dependency into the method that uses the dependency!

Why should we be careful when designing interfaces?
Interfaces allow us to decouple from objects.
This allows us to change class methods without breaking dependencies.
However,
If we change the methods required in our interfaces, we need to recompile all the dependencies!
What is the interface segregation principle?
A very important topic in OOP
divide big fat interfaces into smaller lighter interfaces
Why?
Reduce impact of changes!

What should we avoid in designing our interfaces?
Mixing concerns or capabilities
Why?
If a class implements the interfaces but doesn’t use a method and you later change the method, it will still have to be recompiled!
Every time interfaces change classes dependent on these get affected!
What does the interface segregation principle say we should do?
Each interface should focus on a single capability!
We should divide the interface into smaller ones!
Each one focused on a single capability.
How can we work with multiple interfaces?
Use inheritance
One interface can inherit from another interface!
This allows us to use methods from both interfaces while avoiding fat large interfaces with many coupling points!

What is an intelliJ shortcut for generating an interface?
Refactor menu -> extract -> interface

What can an interface have in Java?
Multiple parents!