Programming II Refresher
Constructors and Classes
Constructors
Constructors appear very similar to methods. They always have the
same name as the class they are created in, have no return type
(not even ‘void’), and cannot be ‘static.’
Constructors are only called when an instance of a class is created
(aka an object). If we don’t create a constructor inside of a class, a
“default constructor” is used in the backend that we cannot see.
Note: by default, the default constructor uses the same access modifier as the class it is in.
Constructors – Default Constructor
You might not realize it, but whenever we create a class in Java,
the “default constructor” is there (although we cannot see it).
The “default constructor” is used when we have no other custom
constructors in our class. It doesn’t have any parameters, which is
why we never needed to provide values whenever we created an
object so far.
However, if the default constructor was visible, this is what it would
look like:
Remember, a constructor will always have the
same name as the class it is in!
Constructors – Default Constructor
When we create an instance of the ‘Computer’ class, the
constructor of the ‘Computer’ class is called. In this case, nothing
happens because the constructor does not have any code within its
body. We created a constructor in the left code snippet that does
the same thing as the default constructor in the right code snippet.
Remember, you cannot visually see the default constructor!
Constructors – Custom Constructors
Generally, we could put any code into this constructor that we
could put into a method. That includes things like if statements,
loops, and more. Let’s put a print statement into it and see what
happens when we run this code…
Output
Why Use Custom Constructors?
Let’s say we created a class called ‘Computer’ and each object of
the “Computer” class has its own attributes.
If we create a custom constructor in the ‘Computer’ class, we can
assign values to each attribute at the time we create an object of
‘Computer’
Let’s go over some more examples of constructors to get a better
idea…
Constructors – Custom Constructors
A constructor that has parameters is known as a “Parameterized
Constructor.” We can use these parameters to assign values to the
attributes of an object when the object is created.
Constructors – Custom Constructors
Notice the three constructor
parameters: processorName,
gigabytesOfRAM, and
gogabytesOfStorage.
Due to this parameterized
constructor, every time we create an
object of ‘Computer,’ we need to
provide values for the parameters.
That’s exactly what we do here in
the main method.
Constructors – Custom Constructors
Inside of the constructor, we assign
the values entered at the object’s
creation to the instance variables for
that object so they can be accessed
or modified later in our code.
To the left of each equal sign, we
use the key word ‘this’ to tell Java
that we are referencing the instance
variables rather than the constructor
parameters.
Constructors – Custom Constructors
Since we assign values to the attributes when we create an object,
we can access these attributes at any time by typing the name of
the object, a dot, and then the name of an attribute.
The output would be: “Intel i9”
Constructor Overloading
Constructor overloading
works exactly like method
overloading! The only
difference is that we are
dealing with constructors
instead of methods.
Output
Creating Custom Classes
In scenarios like we saw in the
previous slides, we should really
have the ‘main’ method in a
different class, away from the
‘Computer’ class.
Notice how in this snippet
everything and only everything
to do with the ‘Computer’ class
is in the ‘Computer’ class.
Anything else should be in a
different class.
Creating Custom Classes
[Link] file
We can even create a separate file for each
class. I recommend doing this to stay organized,
but the decision is up to you.
Keeping multiple classes in one file won’t cause
any errors, but it’s not very organized.
[Link] file
Here’s an example of another class added into our project (the ‘Car’ class)
Creating Custom Classes
[Link] file [Link] file
[Link] file
Notice how we create an instance of
the car class (the ‘MyCar’ object)
and access one of it’s attributes.
Using Setters and Getters In Custom Classes
The way we accessed attributes (aka instance variables) in the
previous slides will work, but what if we could create methods
specifically for modifying each attribute and other methods
specifically for retrieving each attribute?
That’s where setters and getters come in. Let’s see how that would
work with the ‘Computer’ class…
Adding Setters and Getters to the ‘Computer’ class
When using setters and getters, we usually make the instance
variables private. We do this so they cannot be accidentally
modified. Instead of allowing direct access to them, we use
setters for setting a value to a variable and getters for getting a
value from a variable.
In a perfect program, we should only be able to manipulate or
access instance variables using setter and getter methods.
Adding Setters and Getters to the ‘Computer’ class
Now, to retrieve the value within a variable, such as the
‘processorName’ variable from the ‘Computer’ class, we type the
name of an object (in this case, ‘MyComputer’), a dot, and then
call the ‘getProcessorName’ method.
To set a new value to a variable, such as the ‘processorName’
variable, we type the name of an object (in this case,
‘MyComputer’), a dot, and call the ‘setProcessorName’ method.
Don’t forget to enter values for each parameter.
Adding Setters and Getters to the ‘Computer’ class
What would the output be after running this code? Remember, we
always start at the ‘main’ method.
Output
Adding Setters and Getters to the ‘Car’ class
What would the output be after running this code? Remember, we
always start at the ‘main’ method.
Output
Composition
What is Composition?
Composition is a concept that can be used in Java where two or
more entities are highly dependent on each other.
Composition follows a “Part-Of” Relationship.
For example, if you get rid of a library, you are also getting rid of
the books that are “part-of” that library.
Here’s another example: if you get rid of a car, you are also getting
rid of its engine, since an engine is “part-of” a car.
What is Composition?
Composition is implemented using instance variables.
Looking back at the second example from the last slide…
Let’s assume there’s a ‘Car’ class, which represents a car. Let’s also
assume that there’s another class called ‘Engine.’
We all know that every car has an engine. This means we can make
use of composition in our program by creating an instance variable
called ‘engine’ of type ‘Engine’ inside of the ‘Car’ class.
This instance variable is an object of the ‘Engine’ class!
Let’s See The Code…
Notice the variable
using ‘Engine’ as it’s
data type inside of the
‘Car’ class. Inside the
‘Car’ class, it’s really
just another instance
variable, and we even
include it in the
constructor, even
though its data type is
a class.
By doing this, we are
telling our program
that each object of
‘Car’ has an engine!
More Code…
Now let’s do something with the ‘Engine’ class as
well as the ‘Car’ class!
In the class shown in the screenshot to the right,
we have the ‘main’ method for this program.
Inside of this ‘main’ method, the program asks
the user to enter values for each instance
variable that is in the ‘Engine’ class (such as hp,
torque, numbOfCylinders), followed by the ‘Car’
class (make, model, modelYear, engine).
Notice how ‘engine’ is passed to the
constructor for ‘Car’ and how we can call a
method from the ‘Engine’ class using ‘myCar’
More Composition
We can have as much composition as needed in our program! For
example, we could create a ‘Transmission’ class and create an
instance of it in the ‘Car’ class, just like we did for the engine.
Let’s add code to the ‘main’ method for the
Transmission…
I have now added code to the ‘main’
method that asks the user to enter data
for the instance variables that are in the
‘Transmission’ class (numbOfSpeeds,
type).
Created an instance of the ‘Transmission’
class that holds the values entered by
the user for the instance variables.
Called the ‘changeGear’ method after
creating the object of ‘Car’ and passed
through the number of the gear the
transmission is changing to.
Reminder: ‘startEngine’ method is in the ‘Engine’ class and ‘changeGear’ method is in the ‘Transmission’ class
Now Let’s Run Our Program!
As expected, the program asks the user
questions about their car’s engine, transmission,
and lastly, some general info about the car
itself.
But at the bottom of the output, we see ‘*Vroom
Sound*’, which was printed due to calling the
‘startEngine’ method using the ‘myCar’ object
along with its ‘engine’
Similarly, we see ‘Changing to Gear Number: 1’
in the output due to calling the ‘changeGear’
method using the ‘myCar’ object along with
‘transmission’. We also passed through ‘1’ for
the ‘gearNumb’ parameter to change to 1st gear.
One Last Thing…
You can also directly use composition instance variables to call
methods that are inside of the class that they are an instance of.
For example, if inside of the ‘Car’ class we have an instance
variable that is an instance of the ‘Engine’ class, we can use this
instance variable to call any method that is within the ‘Engine’
class. I know, that’s a lot. The next slide will make this clearer…
One Last Thing…
Here is an example of what was
explained on the last slide…
Two composition instance variables
(‘engine’ and ‘transmission’)
Calling methods from classes that the
instance variables are an instance of
(‘startEngine’ in ‘Engine’
‘changeGear’ in ‘Transmission’)
One Last Thing… From ‘Car’ class:
Using the method
we created in the
last slide, we can
adjust our code in
the ‘main’ method
to call this new
method instead of
calling
‘startEngine’ and
‘changeGear’
separately.
And of course, you can add getters and setters to the ‘Engine’ class, ‘Transmission’
class, and the ‘Car’ class!
Adding Getters and Setters
Getters and Setters for ‘Engine’ class
Getters and Setters for ‘Transmission’ class
See next slide for the
getters and setters that
could be added to the
‘Car’ class…
Adding Getters and Setters
Setters for ‘Car’ class
Getters for ‘Car’ class
Example – Calling Getters
In the code snippet below, using the ‘myCar’ object and the getters we created earlier, we
can retrieve ‘myCar’s instance variable values. This includes the ‘engine’ and
‘transmission’ instance variables, which we can use to call getters from the ‘Engine’ class
as well as the ‘Transmission’ class, respectively.
In the ‘main’ method of the ‘CompositionExample’ class:
Example – Calling Setters
In the code snippet below, using the ‘myCar’ object and the setters we created earlier, we
can change ‘myCar’s instance variable values. This includes the ‘engine’ and ‘transmission’
instance variables! We can create a new instance of ‘Engine’ or ‘Transmission’ and set it to
any car object, such as the ‘myCar’ object.
In the ‘main’ method of the ‘CompositionExample’ class:
Inheritance
What is Inheritance?
“Inherit” means to rightfully acquire something from someone or
something.
Let’s say someone has a parent who has blue eyes and black hair.
And let’s say that their child has inherited these traits from them.
The same goes for inheritance in programming.
If a class inherits another class, it is a child class that is inheriting a
parent class.
This child class can access all of its parent class’ variables and
methods, since it inherited them from the parent class.
Terms to Know & Example of Inheritance
Superclass: a class being extended by another class. Also known as a
parent class. In the code snippets below, class ‘A’ is a superclass.
Subclass: a class that extends another class. Also known as a child class. In
the code snippet below, class ‘B’ is a subclass.
Extends: the ‘extends’ key word means ‘inherits.’ For example, if class
‘B’ extends class ‘A,’ class ‘B’ inherits everything from class ‘A,’ meaning
that all non-private methods and variables from class ‘A’ can be accessed
by class ‘B’ or by an instance (an object) of class ‘B’
More to Know…
However, it’s important to understand that only the subclass (class ‘B’)
can access what is in the superclass (class ‘A’), not the other way around.
Class ‘A’ would have to extend class ‘B’ in order for it to access what’s
inside of class ‘B’
*You cannot have ‘B’ extend ‘A’ and ‘A’ extend ‘B’ at the same time.
Creating an Object of a Subclass
If you create an object of the subclass (class ‘B’), that object can access
everything that is in the superclass (class ‘A’), except for anything in ‘A’
that is ‘private’.
What do you think the output would be after running the code below?
Remember, everything from class ‘A’ is inherited by class ‘B’ in this case.
Output:
17
28
Creating an Object of a Subclass
If you create an object of class ‘A’, the superclass, in class ‘B’, the
subclass would you be able to use this object to access the variable
‘question’ that is inside of class ‘B’?
No. Any object of class ‘A’
can only access what is
inside of class ‘A’, since it
does not inherit any other
classes.
In other words, class ‘B’
inherits ‘A’, class ‘A’ does
not inherit ‘B’!
Java Does Not Support Multiple-Inheritance
Since Java does not support multiple-inheritance, you cannot
extend more than one class from another class.
More Complex Example of Inheritance
The subclass, ‘Person’, inherits the
superclass, ‘Questions’, and due to this, an
object of ‘Person’ can access everything that
is not ‘private’ inside of ‘Questions’
Inheritance With Constructors
So far, inheritance should seem pretty easy. Once you extend a class to
another class, you can access virtually all of its code, and that’s all
that’s to it.
Here’s where inheritance starts to get a little more complicated…
What if both classes use a custom constructor instead of the default
constructor, and then you create an object of the subclass or the
superclass? Which constructor would be called??
Let’s go over a couple examples of this…
Non-Parameterized Constructor: a constructor with no parameters.
Scenario 1 – Non-Parameterized Custom
Constructors (Creating Object of Subclass)
Let’s see what the output would be…
Output:
When creating an object of the subclass, it appears as if A’s Constructor
the superclass’ constructor is called and then the subclass’ B’s Constructor
constructor is called, but that is not quite the case…
*‘super’ calls the constructor of the superclass*
Scenario 1 – Non-Parameterized Custom
Constructors (Creating Object of Subclass)
What’s really happening here is that the subclass’
constructor is being called first, it’s just that right
away inside of it, ‘super’ is automatically called,
which is used to call the constructor of the
superclass.
Then, after the constructor of the superclass has
run, we finish running the rest of the code that is in
the subclass’ constructor.
*When dealing with non-parameterized constructors
in inheritance, ‘super’ is called automatically,
meaning we don’t need to have it in our code unless
we are working with parameterized constructors in
inheritance.
Non-Parameterized Constructor: a constructor with no parameters.
Scenario 1 – Non-Parameterized Custom
Constructors (Creating Object of Superclass)
What do you think the output would be
after running this code?
When creating an object of the superclass, the superclass’ Output:
constructor is the only one that is called, since it doesn’t A’s Constructor
inherit any other constructors from other classes.
*Remember, when we call ‘super’, we are just calling the superclass’ constructor*
Scenario 2 – Parameterized Custom
Constructors
In this example, we have parameterized constructors (constructors that have parameters). This
means we need to manually call ‘super’ at the first line inside of the subclass’ constructor. Notice
how we pass values to the superclass’ constructor parameters when we call ‘super’
Also note that the inherited instance variables
appear in the subclass’ constructor!
Polymorphism
What is Polymorphism?
“Poly” means “many” and “morphs” means “to change form”
Therefore, Polymorphism simply means “to have many forms.”
The two types of polymorphism in Java are:
• Compile-Time Polymorphism: Method Overloading
• Runtime Polymorphism: Method Overriding
Compile-Time Polymorphism – Method
Overloading
Method Overloading is the most common type of Compile-Time
Polymorphism and is the only notable type of compile-time
polymorphism supported by Java.
Method Overloading allows multiple methods to have the same
name, but different parameters.
Using method overloading, you can call any version of the method
being overloaded depending on what best suits your program’s
needs.
Method Overloading
There are many ways to perform Method Overloading
In a method that is overloading another method…
• The number of parameters could be different.
• The data types of the parameters could be different.
• The order of the parameters could be different.
Additionally, you could combine any of these into one method.
Method Overloading – Changing Number of
Parameters and Using Different Data Types
This is an example of two ways we can overload a
method:
1. Using a different number of parameters.
2. Using different data types for the parameters.
Notice how when we try calling ‘printInfo’ within
the ‘main’ method it shows all of the options for
each version of the ‘printInfo’ method. We can
call any of the three versions of the method,
thanks to Method Overloading!
You can overload a method as many times as
needed. In this example, we overload the
‘printInfo’ method twice.
Method Overloading – Changing Number of
Parameters and Using Different Data Types
Let’s try calling each version of this method and see what the output would look
like…
Output
Method Overloading – Changing Parameter Order
The third way we could overload a
method is by simply changing the order
of the parameters in the overloading
method.
Notice how in the original method, the
‘name’ parameter is created before
the ‘age’ parameter, but in the
overloading method, it’s the reverse.
Note: this only works if the parameters
are of different data types!
Method Overloading – Changing Parameter Order
Let’s try calling both versions of this method and see what the output would look
like…
Output
Method Overloading
It’s important to know that you
cannot overload a method just
by changing the return type in
the overloading method!
The only way you can overload
a method is by having different
parameters in the overloading
method.
Runtime Polymorphism – Method Overriding
Method Overriding is the most common type of Runtime
Polymorphism and is the only notable type of runtime
polymorphism supported by Java.
Method Overriding allows us to have a method with the same
name in the superclass and the subclass.
The overriding version of the method will always be the one that
is in the subclass and should have ‘@Override’ directly above it.
Method Overriding
How do I know which version of the method is being called?
When you call the method using an object of the subclass, the
overriding method is the one that gets called. The overriding
method is always the one in the subclass.
When you call the method using an object of the superclass, the
original method is the one that gets called. The original method is
always the one in the superclass.
Method Overriding Example 1
What do you think the output will be?
Don’t overthink this.
Output
Hello, I am the subclass!
Hello, I am the superclass!
Note: having @Override above the overriding method is recommended, but not required.
Method Overriding Example 2
This is a more real-world example similar to the last one where we call both versions of
an overridden method.
Method Overriding
What if we want to call the original method that is in the
superclass using an object of the subclass?
We can do this by entering ‘super.(put name of method here)’ inside
of the overriding version of the method (the one that is in the
subclass).
Let’s see how this works on the next slide…
Method Overriding Example 3
Having ‘[Link]()’ in the overriding
version of the ‘sayHi’ method calls the
original version of the method (the one that is
in the superclass, ‘Parent’).
Method Overriding Example 4
This is very similar to example 2. The only difference is that here we are using ‘super’ to
call the original version of the ‘printInfo’ method from the superclass rather than have
repeating print statements in both methods.
User Enters:
student
Robert
24
4.0
Output:
Robert
24
4.0
Worth Noting
To better understand the key word ‘super,’ keep in mind that it
always has something to do with accessing something within the
superclass.
Method Overriding
Are there restrictions to method overriding?
Yes…
‘static’ methods cannot be overridden. In this case, you would just
use the class itself to call the method you would like to call, rather
than using an object.
‘private’ methods cannot be overridden. ‘private’ restricts a
method to only being accessible by objects of the class, or by the
class itself that it was created in.
Both versions of the method must have the same return type.
Method Overriding Example 5
You can have as many subclasses to one superclass as needed! In
this example, there is a superclass called ‘Person’ that has two
subclasses: ‘Student’ and ‘Professor’
Exception Handling
What is an Exception and Exception Handling?
Exception: an unwanted or unexpected event that may occur during
the execution of a program (during runtime). This type of event
disrupts the flow of the program.
Exception Handling: used to handle exceptions if they occur in a
program. Handling exceptions is important in order to preserve the
flow of the program.
When Might an Exception Occur?
An exception can occur in many scenarios, but a few common
example scenarios would be:
• Invalid user input (such as entering the wrong data type).
• Attempting to open a non-existent file.
• Attempting to assign a value to an index of an array past the
highest index number of the array.
Is an Exception the same as an Error?
No, an exception is not the same as an error.
Examples of errors (or when errors could occur) would be a stack
overflow, the Java Virtual Machine (JVM) running out of memory,
corrupted files in IntelliJ, Java, your project, or the JVM, and
physical computer related issues.
Try Running This Code and Entering Anything
Other Than a Number
Does the print statement at
the bottom get ran?
Not if you enter anything
other than a number,
because an exception is
thrown, causing the program
to stop running.
Exception Handing With ‘try-catch’
With the help of ‘try-catch’, if
you enter anything other than a
number, an exception is still
thrown, but it is caught.
This means that the program will
exit the ‘try’ block of code and
begin running the ‘catch’ block
of code.
After that, it will then continue
running code below the ‘try-
catch’ (in this case, the print
statement at the bottom)
Exception Handing With ‘try-catch’
After the key word ‘catch’, you
see ‘Exception e’ inside of
parenthesis. This makes ‘e’ an
object of type ‘Exception’
Printing ‘e’ inside of the ‘catch’
block tells the user (in the
console) what type of exception
was caught while running the
‘try’ block.
Can I put any Code in the ‘catch’ Block?
Yes, you can put any code inside of
the ‘catch’ block, including
recursively calling the method the
‘try-catch’ is in!
In this code snippet, we run the
same code in the ‘try’ block as we
did on the last slide, but this time if
an exception is caught, we tell the
user to try again and call the method
containing the ‘try-catch’ again to
give the user another chance.
This keeps repeating until the user
enters an ‘int’ value (a number).
Different Exception Types Built Into Java
Now that we know how to catch any exception using the type
‘Exception’, we should go over how to catch specific types of
exceptions.
Here are some of the common types of exceptions you can catch:
• ‘InputMismatchException’
• ‘ArrayIndexOutOfBoundsException’
• ‘IOException’
• ‘NullPointerException’
• ‘NumberFormatException’
InputMismatchException
InputMismatchException: this type of exception occurs when the
user enters a value of the wrong datatype into the console (while
using a Scanner or something similar).
Scenario 1 Output
Scenario 2 Output
ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException: this type of exception occurs when your
program tries to assign a value to a non-existent index of an array. For example, if
we have an array of size 3 and try assigning a value to index 3 or higher, this
exception will occur.
It also occurs when trying to access a value at a non-existent index of an array.
Output:
IOException
IOException: this type of exception occurs when our program fails to
write to or read a file from the user’s computer. Most commonly, this
would occur when there is a permissions related issue or a directory
related issue (ex: the file you are trying to read may not exist).
If the program does not have permission to
access the “Users” folder, or the “Users” folder
does not exist, the IOException will be thrown
and caught.
“File failed to output/failed to be written” will
then be printed.
Note: String variables are considered objects since Strings are a non-primitive data type.
NullPointerException
NullPointerException: this exception occurs when your program attempts
to compare a null object to another object using the ‘equals’ method. It
may also occur when trying to perform other similar tasks with a null
object (in this case, ‘name’ is the null object).
NumberFormatException
NumberFormatException: this exception occurs when your program
fails to convert a String to an int. In the example below, the String
contains a ‘,’ which is not a number. This throws the
NumberFormatException, which is then caught. If we removed the
‘,’ from the String, no exception would occur.
Multiple ‘catch’ Blocks
Now that we know about
the common types of
exceptions that could
occur in a program, it’s
good to know that we
can have as many
‘catch’ blocks attached
to one ‘try’ block as
necessary.
Recursion
Recursion – Stack Overflow
(Do not try this at home)
• Recursion works similarly to loops,
where a block of code is run repeatedly.
• To the right is a simple example of
recursion being used in Java ->
• Notice how the ‘repeat’ method is called
within itself.
• There is a problem with this code
though… Do you know what it is?
• The problem is that there is nothing
stopping the ‘repeat’ method from being
called over and over again forever!
Recursion – Ending the Recursion
• Just like a loop needs to have an end,
recursion does too.
• In this recursion example, we add a
parameter called ‘count’ to the
‘repeat’ method.
• We can change the value passed to
this parameter each time the ‘repeat’
method is called.
• When the ‘count’ parameter value
becomes ‘0’ the method is not called
again.
Recursion – Ending the Recursion
Let’s see what’s going on here…
• The ‘repeat’ method is called from the
‘main’ method and ‘5’ is passed through
as the value for the ‘count’ parameter.
• When called, the ‘repeat’ method prints
something out and then checks to see if
‘count’ is equal to ‘0’ or not.
• If ‘count’ is equal to ‘0’, something else
will be printed. Otherwise, the ‘repeat’
method will recursively be called again
and ‘count – 1’ will be passed through as
the next value for the ‘count’ parameter.
Recursion – What is the output?
The output will be…
The count is:5
The count is:4
The count is:3
The count is:2
The count is:1
The count is:0
I’m done counting…
Recursion – Example 2
• There are other ways to stop a
method from being called endlessly
while implementing recursion.
• Here is an example of another way…
• In this example, we have a class
variable called ‘x’ that is given an
initial value of ‘5’
• Each time the ‘repeat’ method is
called and ‘x’ is not equal to ‘0’, ‘1’
is subtracted from the value of ‘x’
before calling ‘repeat’ again.
Recursion – What is the Output?
The output will be…
The count is:5
The count is:4
The count is:3
The count is:2
The count is:1
The count is:0
I’m done counting…
• The same output as the last example
Class Activity
There are three parts to this class activity.
You only need to complete two of the three parts, however, if you
complete all three, you will get an extra point added to your
assignment grade.
Composition slides: 21-35. Looking at the “Constructors and Classes” slides might help too.
Class Activity – Part 1 (Composition)
• Create a new project and a class called ‘CA2P1’. Put the ‘main’ method
inside of this class.
• Create another class called ‘Display’ and create the following instance
variables within it: ‘resolution’, ‘panelType’
Also create the constructor, getter methods, and a method named
‘printDisplayInfo’ that prints both instance variables when called.
• Create another class called ‘SpeakerSystem’ and create the following
instance variables within it: ‘numbOfSpeakers’, ‘speakerBrand’
Also create the constructor, getter methods, and a method named
‘printSpeakerSystemInfo’ that prints both instance variables when
called.
• Create another class called ‘TV’ and create the following instance
variables within it: ‘brand’, ‘model’, ‘display’ (of type ‘Display’), and
‘speakerSystem’ (of type ‘SpeakerSystem’)
Also create the constructor and the getter methods.
Composition slides: 21-35. Looking at the “Constructors and Classes” slides might help too.
Class Activity – Part 1 (Composition)
• Inside of the ‘main’ method within the ‘CA2P1’ class, ask the user to
enter the info for every instance variable that is in each class. Create an
object of each class (other than ‘CA2P1’), and when doing so, pass the
appropriate values entered by the user as the constructor parameters.
• Use the object of the ‘TV’ class and the ‘display’ instance variable
object to call the ‘printDisplayInfo’ method. After that, similarly, use
the same object of the ‘TV’ class and the ‘speakerSystem’ instance
variable object to call the ‘printSpeakerSystemInfo’ method. Lastly, call
the ‘getBrand’ and ‘getModel’ getter methods using the object you just
created of the ‘TV’ class. Print what the getter methods return (you can
call them within a print statement).
Inheritance slides: 36-48 | Method Overriding slides: 59-64
Class Activity – Part 2
(Inheritance & Method Overriding)
• Create… a class called ‘CA2P2’ that has the ‘main’ method in it, a
superclass called ‘Vehicle’, and a subclass called ‘Airplane’
• Put the following instance variables in the ‘Vehicle’ superclass:
‘seatCount’, ‘powerSource’
• Put the following instance variables in the ‘Airplane’ subclass:
‘numbOfJetEngines’, ‘maxAltitude’
• Set up the appropriate constructors in both classes.
• Create a method in both classes called ‘printInfo’ that prints out
the instance variable’s values for that class (it’s up to you if you
want to create setters and getters and call the getters in this
method). *This method should be overridden in the subclass.
Inheritance slides: 36-48 | Method Overriding slides: 59-64
Class Activity – Part 2
(Inheritance & Method Overriding)
• In the main method of the ‘CAP2’ class, ask the user if the vehicle
is an airplane. If the vehicle is anything other than an airplane,
create an object of ‘Vehicle’, the superclass. If the vehicle is an
airplane, create an object of ‘Airplane’, the subclass. Ask the user
to enter values for the instance variables and pass what they
enter as the parameters for the constructors when creating these
objects.
• Call the ‘printInfo’ method right after each object has been
created (call it using the object that was just created).
Recursion slides: 83-89 | Exception Handling slides: 68-82
Class Activity – Part 3
(Recursion & Exception Handling)
Ask the user to enter the length (the number of elements an array can
hold) for a new array of int values called ‘specialNumbers’.
Then, in a recursively called method, ask the user repeatedly (using
recursion) for an index number that they would like to assign an int value
to. Right after they enter an index number, ask them for an int value to
assign to that index of the array (using a Scanner) and then actually assign
the int value to that index.
Be sure to use exception handling in case the user enters a letter or
special character instead of an ‘int’ value. Also use exception handling to
ensure that the user doesn’t try to assign a value to a non-existent index
of the array. For example, if the array is of size 3, we cannot assign a
value to any index greater than 2.
At the end of every time the user assigns a value to an index, ask them if
they would like to stop or keep going. If they would like to stop, stop
recursively calling the recursive method and print every value that is in
the array using a for loop or a for-each loop.
Submission Instructions
When you are done, show me your work
After that, put screenshots of your code and the output from a
test run into a word document and submit it on Canvas under
“Class Activity 2”