0% found this document useful (0 votes)
14 views

Comp200 Exam Prep

Uploaded by

sasthinaidoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Comp200 Exam Prep

Uploaded by

sasthinaidoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

A variable that can hold a reference to an object of class A can also hold a

reference to an object belonging to any subclass of A: TRUE

A subclass can access all the private members (fields and methods) of its superclass.:
FALSE

A method can be overloaded by changing only the return type: FALSE

An abstract class contains only abstract methods: FALSE

An abstract class in Java can have constructors.: TRUE


**Abstract class constructors are typically invoked implicitly by constructors of their
concrete subclasses

ABSTRACTION → Focusing on essential properties and behaviour of an object, while


ignoring non-essential details., (Abstraction is the process of hiding the implementation details
and showing only functionality to the user.)
ENCAPSULATION → Hiding the internal details of an object from its users and
exposing only the necessary information through access modifiers,
POLYMORPHISM → Allowing objects of different classes to be used interchangeably,
based on their common interface or superclass.,
COMPOSITION → A relationship between classes where one class contains another
class as a part of its state. The contained class cannot exist without the container
class,
INHERITANCE → Creating new classes by inheriting properties and methods from
existing classes.

UML DIAGRAMS SYMBOLISM:


Heading in italics abstract class
Method in italics abstract method
Access modifiers: +  public
-  private
#  protected
~  package

Relationships: INHERITANCE  is an arrow joining the subclass to the superclass


COMPOSITION  coloured in diamond
AGGREGATION open diamond
ASSOCIATION  just a line joining two classes
INTERFACE  dotted line with arrow?
INNER CLASSES SEE PIC…

*when you assign a superclass to a subclass type it will give you compile-time error!*
*The protected modifier allows a member to be accessed in a subclass from a
different package: TRUE

**Constructors are not inherited from a superclass to its subclass:TRUE


 Constructors are defined in each class separately and are not inherited by
subclasses. If one is not defined then the default constructor of the superclass is
implicitly called.

A subclass can only provide a new implementation of a superclass method if the


superclass method was declared as abstract: FALSE
** an override can provide an entirely new definition of a concrete method.

A superclass reference can be directly assigned to a subclass variable without explicit


typecasting: FALSE

A method can be overridden by changing only the return type: FALSE

When methods are overloaded, the method to execute is decided at compile-time:


TRUE

New subclass objects can be assigned to an abstract class variable: TRUE


 can’t instantiate objects from an abstract class BUT you can use it as a reference
(use as variable type).
An abstract class in Java can extend another abstract class: TRUE

All methods declared in an interface are implicitly private: FALSE


An interface can implement multiple parent interfaces: FALSE
* A class implements multiple interfaces

An interface can contain static methods: TRUE

A class can implement multiple interfaces with conflicting default methods as long as
the class overrides the conflicting method and specifies which implementation to
use: TRUE

CLASSA class is a blueprint that defines the state (variables) and the behaviour (methods) of something that
you want to model. Allows for: Abstraction, Encapsulation, Information Hiding

OVERLOADED METHOD: (*Constructors can ONLY be overloaded)

Overloaded methods and constructors let you use the same method name (or constructor) but with different
argument lists.
Overloaded methods let you reuse the same method name in a class, but with different arguments (and
optionally, a different return type).

RULES:
 Overloaded methods must change the argument list.
 Overloaded methods can change the return type.
 Overloaded methods can change the access modifier.
 A method can be overloaded in the same class or in a subclass.
 Referred to as “compile-time polymorphism”

OVERRIDEN METHOD:

Overriding lets you redefine a method in a subclass, when you need new subclass-specific behaviour

RULES:
 The argument list must exactly match that of the overridden method.
 The return type must exactly match that of the overridden method.
 The access level must not be more restrictive than that of the overridden method.
 The access level can be less restrictive than that of the overridden method.
 Referred to as “run-time polymorphism”

INSTANTIATING CLASSES:

REGULAR INNER CLASSES MyOuter mo = new MyOuter(); //instantiate outer class


(instantiate in main class) MyOuter.MyInner inner = mo.new MyInner(); //instantiate inner class
inner.seeOuter();

OR!

MyOuter.MyInner inner = new MyOuter().new MyInner();


inner.seeOuter();

METHOD-LOCAL INNER CLASS MyInner mi = new MyInner(); //instantiate outside inner class but within
method

ANONYMOUS INNER CLASS:


STATIC NESTED CLASS public static void main (String [] args){
BigOuter.Nested n = new BigOuter.Nested();
/ / Use both c l a s s names
}

 a static nested class does NOT have access to the instance variables and methods
of the outer class.

INTERFACES:

system that unrelated entities use to interact


consists of a set of method interfaces with no associated implementation
Beware of the “deadly diamond of death” Methods with the same name and signature in both the super-
class and sub-class (no multiple inheritance)
solution to the diamond problem: default methods in interfaces
An interface may EXTEND ONE OR MORE interfaces. (Interfaces are not classes and do not implement other
interfaces)
DIFFERENCES BETWEEN INTERFACES AND ABSTRACT CLASSES:

An interface cannot implement any methods, whereas an abstract class can.
A class can implement many interfaces but can have only one superclass.
An interface is not part of the class hierarchy.
Unrelated classes can implement the same interface.

Describe two (2) benefits of using anonymous classes for event handling in
Java [4]

Enhanced Encapsulation: Anonymous classes help in encapsulating the event handling logic within
the scope of the component that triggers the event.

Concise and Localized Code: Anonymous classes enable you to define and instantiate event
handlers in a single, succinct block of code, directly within the context where the event handling is
needed. This makes the code more readable and maintainable because the event handling logic is
placed right next to the code that triggers the event.

For example, when adding an action listener to a button, you can define the listener immediately:

Describe briefly (in not more than one or two sentences) the following concepts
used in object-oriented programming:
(a) encapsulation Encapsulation is the practice of bundling the data (attributes) and methods (functions)
that operate on the data into a single unit or class, and restricting access to some of the object's components to
protect the object's internal state from unintended interference and misuse.

(b) inheritance Inheritance is a mechanism where a new class (subclass or derived class) inherits the
properties and behaviors (fields and methods) of an existing class (superclass or base class), allowing for code
reuse and the creation of hierarchical relationships between classes.

(c) polymorphism Polymorphism is the ability of objects of different classes related by inheritance to
respond to the same method call in a way that is specific to their own class, enabling a single interface to
represent different underlying forms (data types).

(d) abstract methods Abstract methods are methods declared in an abstract class or interface that do not
have an implementation and must be overridden by subclasses or implementing classes, forcing them to
provide specific behavior for the method.
(e) interfaces (specifically in Java) Interfaces in Java are abstract types that define a set of method
signatures without implementing them, allowing classes to implement multiple interfaces and thereby support
multiple inheritance of behavior.

In object-oriented design, aggregation, composition and inheritance are three common


relationships between classes. Explain briefly what each of these relationships entails.

Aggregation: is a relationship where one class (the whole) contains references to one or more objects of
another class (the parts), but the lifecycle of the parts is independent of the whole. In other words, the parts
can exist independently of the whole. This is often described as a "has-a" relationship. For example, a library
has books, but the books can exist independently of the library.

Composition: is a stronger form of aggregation where the whole class owns the parts, and the lifecycle of the
parts is dependent on the whole. If the whole object is destroyed, the parts are also destroyed. This represents
a "contains-a" relationship with strong ownership. For example, a house contains rooms, and if the house is
demolished, the rooms no longer exist.

Inheritance: is a relationship where a new class (derived or subclass) is based on an existing class (base or
superclass), inheriting its attributes and methods. This allows the derived class to reuse and extend the
functionality of the base class. It represents an "is-a" relationship. For example, a car is a vehicle, meaning a car
class can inherit from a vehicle class.

Explain the purpose of Java’s layout managers in GUI programming and briefly describe how any one such
layout manager operates.

FlowLayout: FlowLayout is one of the simplest layout managers in Java. It arranges components in
a left-to-right flow, much like lines of text in a paragraph. When the container's edge is reached,
FlowLayout wraps the components to the next line.

Here's a brief description of how FlowLayout operates:

1. Component Order: Components are added to the container in the order they are specified.
2. Alignment: Components can be aligned to the left, center, or right of the container.
3. Wrapping: If the horizontal space is insufficient to fit all components in a single row,
FlowLayout wraps the components to a new line below.
4. Spacing: FlowLayout allows setting horizontal and vertical gaps between components.

BorderLayout

Description: BorderLayout divides the container into five regions: North, South, East, West, and
Center. Each region can contain only one component, and components added to these regions are
resized to fit the region.

How it operates:
 North and South: These regions extend horizontally across the container, at the top and
bottom, respectively.
 East and West: These regions extend vertically along the left and right edges of the container.
 Center: This region takes up all the remaining space in the center.

GridLayout

Description: GridLayout arranges components in a grid of cells with equal size, each cell containing
one component. The grid is defined by a specified number of rows and columns.

How it operates:

 Uniform Size: All cells in the grid are of equal size.


 Row and Column Specification: The number of rows and columns can be specified when
creating the GridLayout. If one dimension is set to 0, the layout will automatically adjust to
accommodate all components.
 Components Placement: Components are placed in the grid from left to right, top to bottom.

What does the super.paintComponent(g) statement do? Can this statement


safely be left out of the code and still have the code execute correctly? (2)

It does any drawing in the super class of the panel in which it is located. In this case,
we could actually leave it out and the code would still work. But it’s very bad practice
to do so, since it makes our code vulnerable to bugs if and when it gets changed. For
example, if we wanted to make a background colour for the panel, we might do this in
the constructor. That’s actually what I did in the solution to Q4 (see Test2.java). This
is drawn by super.paintComponent(). Leaving it out would then mean the background
isn’t drawn.

The ClickListener class extends the MouseAdapter class to handle mouse click
events. A separate class could instead have been written to implement the
MouseListener interface. Explain what the purpose of the MouseAdapter class is,
and why it is used here in preference to a separately written class which
implements the MouseListener interface. (2)

The MouseAdapter class is a convenience class which provides a dummy implementation


of all the methods in the MouseListener injterface. Since in a particular application we
very often actually only require one or two of the methods in the interface, it’s easier to
extend MouseAdapter and just override those methods that we do need, rather than to
do a full implementation of the interface. Were we to implement the MouseListener
interface fully ourselves, those methods that we didn’t need would no doubt just have
dummy implementations anyway.
Here we only need the mouseClicked method, so we extend MouseAdapter and just
override mouseClicked.
Distinguish clearly between the following pairs of terms

overridden and overloaded methods.


Overloaded methods and constructors let you use the same method name (or constructor) but with
different argument lists. Overloaded methods must change the argument list, they can change the return
type and the access modifier. A method can be overloaded in the same class or in a subclass.

Overriding lets you redefine a method in a subclass, when you need new subclass-specific behavior.
The argument list and the return type must exactly match that of the overridden method. The access
level must not be more restrictive than that of the overridden method.

single inheritance and multiple inheritance


In single inheritance, a class is allowed to extend only one base class while in multiple
inheritance, a class may extend more than one base class.

Explain the meaning of the following terms as used in object-oriented programming.

Polymorphism A method is polymorphic if the action performed by the method depends on the
actual type of the object to which the method is applied. Different objects can respond to the
same message in different ways.

generic programming Generic PROGRAMMING refers to writing code that will work for many
types of data for example sort routines.

static methods Are per-class methods. They are associated with the class and not objects. They
cannot reference instance variables or methods.

State and explain TWO differences between interfaces and abstract classes.

• Abstract classes may contain implemented and abstract methods; while interfaces may only contain
unimplemented or abstract methods.

• Abstract classes are extended while interfaces are implemented.

• Abstract classes may have instance fields (variables) while all variables in an interface are implicitly final
(constants).

• All methods and fields in an interface are implicitly public while methods in an abstract class may be private...

anonymous inner class Anonymous inner classes are local inner classes that have no name. Anonymous
classes can be defined as expressions and instantiated on the fly. An instance of a local (or an anonymous) class
has an enclosing instance associated with it, if the local (or anonymous) class is declared in a non-static context.

composition Composition: (’has-a’ relationship between two classes. One class contains references to objects
of other classes e.g. a A database class contains instances of CD objects.)
State the difference between checked and unchecked exceptions. Is NegativeValueExcepion a checked or
unchecked exception? 4
Checked exceptions describe a problem that is likely to occur at times, no matter how careful you are not
your fault. They are normally due to external failures beyond your control, such as deleted file, server crashing,
network outage, etc. ClassNotFoundException, IOException, EOFException, FileNotFoundException,
UnknownHostException. The compiler insists you handle checked exceptions those that you cannot prevent

Unchecked exceptions fall under the RunTimeException class and are due the fault of the programmer,
RunTimeException, ArrayIndex- OutOfBoundsException, ArithmeticException, NullPointerException,
ClassCastException. You are not compelled to handle checked exceptions.

NegativeValueExcepion is a checked exception.

The class Cat is a subclass of the class Mammal. Explain by means of suitable code
segments when and where the special Java variables this and super will be required
within the subclass. [4 ]

this: is a reference to the current object. Can be used to access members of the class e.g. this.x.
Useful for unambiguous referencing.

Super is a reference to the super class. Used to call super class constructors (super()) or super class
methods and variables super.x().

The application uses an inner class for the button event handling. An anonymous
inner class may be used instead. Write code that adds a button to the interface that,
when clicked, changes the color of the rectangle to yellow. Use an anonymous
class for the event handling. JButton yellow = new JButton(" Yellow ");
yellow.addActionListener(new ActionListener (){
class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){
public void actionPerformed(ActionEvent e){ current = Color.yellow;
current = Color.green; repaint();
repaint(); }
} });
} add(yellow);

You might also like