0% found this document useful (0 votes)
394 views14 pages

OOP Reviewer Final Exam

Uploaded by

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

OOP Reviewer Final Exam

Uploaded by

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

OOP Reviewer

Object-Oriented Programming (OOP)


Object-Oriented Programming (OOP)
➢ is an approach to problem-solving where all computations are carried out using
objects.
➢ An object is a component of a program that knows how to perform certain
actions and how to interact with other elements of the program.
➢ Objects are the basic units of object-oriented programming. A simple example of
an object would be a person.
➢ Logically, you would expect a person to have a name. This would be considered
a property of the person. You would also expect a person to be able to do
something, such as walking. This would be considered a method of the person.
➢ A method in object-oriented programming is like a procedure in procedural
programming. The key difference here is that the method is part of an object. In
object-oriented programming, you organize your code by creating objects, and
then you can give those objects properties and you can make them do certain
things.
➢ A key aspect of object-oriented programming is the use of classes.
➢ A class is a blueprint of an object.
➢ You can think of a class as a concept, and the object as the embodiment of that
concept. So, let's say you want to use a person in your program. You want to be
able to describe the person and have the person do something. A class called
'person' would provide a blueprint for what a person looks like and what a
person can do. Examples of object-oriented languages include C#, Java, Perl
and Python.
OBJECTS AND CLASSES IN JAVA
Object
➢ An object represents an entity in the real world that can be distinctly identified. For
example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects.
➢ An object has a unique identity, state, and behaviors.
➢ The state of an object is represented by data fields (also known as properties) with their
current values.
➢ The behavior of an object is defined by a set of methods. Invoking a method on an object
means that you ask the object to perform a task.
Class
➢ A class is a template or blueprint that defines what an object's data and methods will be. An
object is an instance of a class.
➢ You can create many instances of a class.
➢ Creating an instance is referred to as instantiation.
➢ The terms object and instance are often interchangeable.
➢ A Java class uses variables to define data fields and methods to define behaviors.
Additionally, a class provides methods of a special type, known as constructors, which are
invoked when a new object is created.
CONSTRUCTORS
➢ A constructor is a special kind of method. A constructor can perform any action, but
constructors are designed to perform initializing actions, such as initializing the data fields of
objects
➢ A class may be declared without constructors. In this case, a no-arg constructor with an
empty body is implicitly declared in the class. This constructor, called a default constructor,
is provided automatically only if no constructors are explicitly declared in the class.
➢ Constructors are a special kind of method, with three differences:
• Constructors must have the same name as the class itself.
• Constructors do not have a return type—not even void.
• Constructors are invoked using the new operator when an object is created.
• Constructors play the role of initializing objects.
CLASS AND OBJECTS CAN BE REPRESENTED USING UML DIAGRAMS
➢ Unified Modeling Language (UML)
➢ UML is used to standardized classes templates and objects

➢ In the class diagram, the data field is denoted as


• dataFieldName: dataFieldType
➢ The constructor is denoted as
• ClassName(parameterName: parameterType)
➢ The method is denoted as
• methodName(parameterName: parameterType): returnType
➢ CAUTION:
• It is a common mistake to put the void keyword in front of a constructor. For
example,
• public void Circle() {
}
ACCESSING OBJECTS VIA REFERENCE VARIABLES
➢ Objects are accessed via object reference variables, which contain references to the
objects. Such variables are declared using the following syntax:
➢ ClassName objectRefVar;
➢ A class defines a type, known as a reference type. Any variable of the class type can
reference to an instance of the class. The following statement declares the variable
myCircle to be of the Circle type:
➢ Circle myCircle;
➢ The variable myCircle can reference a Circle object. The next statement creates an object
and assigns its reference to myCircle.
➢ myCircle = new Circle();
➢ Using the syntax shown below, you can write one statement that combines the declaration
of an object reference variable, the creation of an object, and the assigning of an object
reference to the variable.
➢ ClassName objectRefVar = new ClassName();
➢ Here is an example:
➢ Circle myCircle = new Circle();
ACCESSING AN OBJECT'S DATA AND METHODS
➢ After an object is created, its data can be accessed and its methods invoked using the dot
operator (.), also known as the object member access operator:
➢ objectRefVar.dataField references a data field in the object.
➢ objectRefVar.method(arguments) invokes a method on the object
VISIBILITY MODIFIERS
➢ Java provides several modifiers that control access to data fields, methods, and classes.
public makes classes, methods, and data fields accessible from any class.
• private makes methods and data fields accessible only from within its own class.
• If public or private is not used, then by default the classes, methods, and data fields
are accessible by any class in the same package. This is known as package-private
or package-access.
DATA FIELD ENCAPSULATION
➢ To prevent direct modifications of properties, you should declare the field private, using the
private modifier. This is known as data field encapsulation.
➢ A private data field cannot be accessed by an object through a direct reference outside the
class that defines the private field. But often a client needs to retrieve and modify a data
field.
➢ To make a private data field accessible, provide a get method to return the value of the data
field. To enable a private data field to be updated, provide a set method to set a new value.
➢ NOTE:
• Colloquially, a get method is referred to as a getter (or accessor), and a set method
is referred to as a setter (or mutator).
A GET METHOD HAS THE FOLLOWING SIGNATURE:
➢ public returnType getPropertyName()
• If the returnType is boolean, the get method should be defined as follows by
convention:
➢ public boolean isPropertyName()
➢ public void setPropertyName(dataType propertyValue)
Advance concepts in Java
Abstraction
➢ Abstraction aims to hide complexity from users and show them only relevant information.
For example, if you’re driving a car, you don’t need to know about its internal workings.
➢ The same is true of Java classes. You can hide internal implementation details using
abstract classes or interfaces. On the abstract level, you only need to define the method
signatures (name and parameter list) and let each class implement them in their own way.
➢ Abstraction in Java:
• Hides the underlying complexity of data
• Helps avoid repetitive code
• Presents only the signature of internal functionality
• Gives flexibility to programmers to change the implementation of abstract behavior
• Partial abstraction (0-100%) can be achieved with abstract classes
• Total abstraction (100%) can be achieved with interfaces
Encapsulation
➢ Encapsulation helps with data security, allowing you to protect the data stored in a class
from system-wide access. As the name suggests, it safeguards the internal contents of a
class like a capsule.
➢ You can implement encapsulation in Java by making the fields (class variables) private and
accessing them via their public getter and setter methods. JavaBeans are examples of fully
encapsulated classes.
➢ Encapsulation in Java:
• Restricts direct access to data members (fields) of a class
• Fields are set to private
• Each field has a getter and setter method
• Getter methods return the field
• Setter methods let us change the value of the field
Polymorphism
➢ Polymorphism means many (poly) shapes (morph)
➢ In Java, polymorphism refers to the fact that you can have multiple methods with the same
name in the same class
➢ There are two kinds of polymorphism:
• Overloading
▪ Two or more methods with different signatures
• Overriding
▪ Replacing an inherited method with another having the same signature

Why overload a method?


➢ So, you can use the same names for methods that do essentially the same thing
• Example: println(int), println(double), println(boolean), println(String), etc.
➢ So, you can supply defaults for the parameters:
int increment(int amount) {
count = count + amount;
return count;
}
int increment() {
return increment(1);
}
➢ Notice that one method can call another of the same name
➢ So, you can supply additional information:
void printResults() {
System.out.println("total = " + total + ", average = " + average);
}
void printResult(String message) {
System.out.println(message + ": ");
printResults();
}

Overriding
➢ This is called overriding a method
➢ Method print in Dog overrides method print in Animal
➢ A subclass variable can shadow a superclass variable, but a subclass method can
override a superclass method
How to override a method
➢ Create a method in a subclass having the same signature as a method in a superclass
➢ That is, create a method in a subclass having the same name and the same number and
types of parameters
• Parameter names don’t matter, just their types
➢ Restrictions:
• The return type must be the same
• The overriding method cannot be more private than the method it overrides
More about toString()
➢ It is almost always a good idea to override
➢ public String toString()
➢ to return something “meaningful” about the object
➢ When debugging, it helps to be able to print objects
➢ When you print objects with System.out.print or System.out.println, they automatically call
the objects toString() method
➢ When you concatenate an object with a string, the object’s toString() method is
automatically called
➢ You can explicitly call an object’s toString() method
➢ This is sometimes helpful in writing unit tests; however...
➢ Since toString() is used for printing, it’s something you want to be able to change easily
(without breaking your test methods)
➢ It’s usually better to write a separate method, similar to toString(), to use in your JUnit tests
Calling an overridden method
➢ When your class overrides an inherited method, it basically “hides” the inherited method
➢ Within this class (but not from a different class), you can still call the overridden method, by
prefixing the call with super.
• Example: super.printEverything();
➢ You would most likely do this in order to observe the DRY principle
• The superclass method will do most of the work, but you add to it or adjust its results
• This isn’t a call to a constructor, and can occur anywhere in your class (it doesn’t
have to be first)
Summary
➢ You should overload a method when you want to do essentially the same thing, but with
different parameters
➢ You should override an inherited method if you want to do something slightly different than
in the superclass
• It’s almost always a good idea to override public void toString() -- it’s handy for
debugging, and for many other reasons
• To test your own objects for equality, override public void equals(Object o)
• There are special methods (in java.util.Arrays) that you can use for testing array
equality
➢ You should never intentionally shadow a variable
Inheritance
Inheritance
➢ is one of the features of Object-Oriented Programming (OOPs). Inheritance allows a class
to use the properties and methods of another class. In other words, the derived class
inherits the states and behaviors from the base class. The derived class is also called
subclass and the base class is also known as super-class. The derived class can add its
own additional variables and methods. These additional variable and methods differentiate
the derived class from the base class.
➢ Inheritance is a compile-time mechanism. A super-class can have any number of
subclasses. But a subclass can have only one superclass. This is because Java does not
support multiple inheritance.
➢ Superclass - is also referred to as a supertype, a parent class, or a base class.
➢ Subclass – is a subtype, a child class, an extended class, or a derived class. It inherits
accessible data fields and
➢ The keyword used for inheritance is extends. Syntax:
➢ public class ChildClass extends ParentClass {
➢ // derived class methods extend and possibly override
➢ }
➢ The use of the key word: super

GUI IN JAVA
What is GUI in Java?
➢ GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java
applications. It is mainly made of graphical components like buttons, labels, windows, etc.
through which the user can interact with an application. GUI plays an important role to build
easy interfaces for Java applications.
What is Swing in Java?
➢ Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI
components. Swing provides a rich set of widgets and packages to make sophisticated GUI
components for Java applications. Swing is a part of Java Foundation Classes (JFC), which
is an API for Java GUI programing that provide GUI.
➢ The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older,
platform dependent GUI toolkit. You can use the Java simple GUI programming
components like button, textbox, etc., from the library and do not have to create the
components from scratch.
What is a Container Class?
➢ Container classes are classes that can have other components on it. So for creating a Java
Swing GUI, we need at least one container object. There are 3 types of Java Swing
containers.
• Panel: It is a pure container and is not a window in itself. The sole purpose of a
Panel is to organize the components on to a window.
• Frame: It is a fully functioning window with its title and icons.
• Dialog: It can be thought of like a pop-up window that pops out when a message has
to be displayed. It is not a fully functioning window like the Frame.
▪ JPanel, a part of the Java Swing package, is a container that can store a
group of components. The main task of JPanel is to organize components,
various layouts can be set in JPanel which provide better organization of
components, however, it does not have a title bar
▪ JFrame frame = new JFrame("Simple GUI"); What this line does is create a
new instance of a JFrame object called "frame". You can think of "frame" as
the window for our Java application

▪ JDialog is a part Java swing package. The main purpose of the dialog is to
add components to it. JDialog can be customized according to user need.
JDialog(Window o, String t): creates an empty dialog with a specified window
as its owner and specified title.
Action Events
➢ An action event occurs, whenever an action is performed by the user. Examples: When
the user clicks a button, chooses a menu item, presses Enter in a text field. The result is
that an actionPerformed message is sent to all action listeners that are registered on the
relevant component.
SWING Event Listener Interfaces
➢ Following is the list of commonly used event listeners.
• ActionListener
• ComponentListener
• ItemListener
• KeyListener
• WindowListener
• AdjustmentListener
• ContainerListener
• MouseMotionListener
• FocusListener
Action Listener
➢ An ActionListener can be used by the implements keyword to the class definition. It can
also be used separately from the class by creating a new class that implements it. It should
also be imported to your project
How to Write Action Listener in Java
➢ To write an Action Listener, follow the steps given below:
• Declare an event handler class and specify that the class either implements an
ActionListener interface or extends a class that implements an ActionListener
interface. For example:
public class MyClass implements ActionListener {
➢ The implements keyword is used to implement an interface. The interface keyword is used
to declare a special type of class that only contains abstract methods. To access the
interface methods, the interface must be "implemented" (kinda like inherited) by another
class with the implements keyword (instead of extends).
• Register an instance of the event handler class as a listener on one or more
components. For example:
someComponent.addActionListener(instanceOfMyClass);
• Include code that implements the methods in listener interface. For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
➢ Event listeners represent the interfaces responsible to handle events. Java provides various
Event listener classes, however, only those which are more frequently used will be
discussed. Every method of an event listener method has a single argument as an object
which is the subclass of EventObject class. For example, mouse event listener methods will
accept instance of MouseEvent, where MouseEvent derives from EventObject.
JTable
➢ JTable class is a part of Java Swing Package and is generally used to display or edit two-
dimensional data that is having both rows and columns.
➢ Constructors in JTable:
• JTable(): A table is created with empty cells.
• JTable (int rows, int cols): Creates a table of size rows * cols.
• JTable(Object [][] data, Object []Column): A table is created with the specified name
where []Column defines the column names.
➢ Functions of Table
• addColumn(TableColumn [] column): adds a column at the end of the JTable.
• clearSelection(): Selects all the selected rows and columns.
• editCellAt(int row, int col): edits the intersecting cell of the column number col and
row number row programmatically, if the given indices are valid and the
corresponding cell is editable.
• setValueAt(Object value, int row, int col): Sets the cell value as ‘value’ for the
position row, col in the JTable.
Add Columns

Search/Sort
Search Using Mouse Click
➢ The MouseEvent interface represents events that occur due to the user interacting with a pointing
device (such as a mouse). Common events using this interface include click, dblclick, mouseup,
mousedown.

Edit using TextField and Button

GOODLUCK and GODBLESS

You might also like