Object-oriented
programming concepts
Lesson Plan
·
Basics
·
Polymorphism
·
Overriding
methods
·
Interfaces
·
Final
and abstract modifiers
·
Access
modifiers
Basic syntax:
class class_name extends base_class_name
Example:
Compile and
execute the following code:
import
javax.swing.*;
class
SolarSystem extends JFrame {
public static void main(String args[]){
SolarSystem
ss = new SolarSystem();
ss.show();
}
}
What
happens when you execute the code? Try
to explain that
Exercise 4.1
double dist2Point(int px, int py){
return
Math.sqrt((px-x)*(px-x)+(py-y)*(py-y));
}
Try to print a distance from
circle's center to a point (1,1). How can you explain the result (do x and y
belong to an object?)
super();
to the constructor of the circle
class, compile the code again.
double getArea() { return 0;}
to the class Shape. Create an object named
SH of type Shape and objects of type Square and Circle. Cast them onto SH and print area of SH. What does the term
'polymorphism' means?
Overriding methods
Exercise 4.2
Write
a program, which contains two classes: Square and Rectangle, which extends
Square. Both classes should contain a method getArea, with the same signature.
Provide appropriate implementations for methods of both classes. Print out
results.
Interfaces
Interface
definition contains a collection of constants and method declarations. A class
that chooses to use (implement) a specific interface should provide
implementation to every interface method. Objects of different classes, which
implement the same interface, can be declared to be of the same, 'interface'
type. This makes it possible to implement polymorphism without an inheritance.
The following example shows how different methods can be executed, using an
interface:
class
Square implements Geom {
int side=1;
public double getArea(){ return side*side;
}
}
class
Circle implements Geom {
int r=1;
public double getArea(){ return Math.PI*r*r;
}
}
class
startAp {
public static void main(String[] args){
Geom g;
g = new Circle();
System.out.println(g.getArea());
g = new Square();
System.out.println(g.getArea());
}
}
interface
Geom {
public double getArea();
}
A common
use of interfaces is to make them containers for constants shared among various
classes. Every class, which implements an interface, gains an automatic access
to these constants.
Classes,
which cannot be extended further, are declared using a modifier final.
On the contrary, some classes are designed exclusively for the purpose
to be extended. These are abstract classes. The final modifier can be applied to methods
and variables. Variable, which is
defined to be final is just a constant.
Access
modifiers - public and private
The public keyword denoted that the element is
publicly available (available from outside a class). The private – means that it is available only
within a class. Hiding object’s data
from the outside is called encapsulation.
When no
access modifier is specified, a variable has a status "friendly" and it can be accessed from
any class within the same package.
|
Specifier |
class |
subclass |
package |
world |
|
private |
X |
|
|
|
|
protected |
X |
X |
X |
|
|
public |
X |
X |
X |
X |
|
friendly
(default) |
X |
|
X |
|
Object-oriented programming rule:
Make variables private,
access variables through public methods
As long
as it makes sense.
GUI-based JAVA
programs
Elements of
graphical user interface provided by JAVA can be divided into two groups: components and containers.
The former group contains elements such as buttons, canvases, check
boxes, choices etc. GUI components are defined in packages javax.swing (java2) and java.awt (java 1.1) and all of them extend
the class Component. Components do not appear on a screen on their own - they are
always placed within a container. There are two main types of containers
defined in Java: frames and panels. Frames contain a border
and a title bar whereas panels do not.
Rule:
use and customize
ready-made GUI building blocks.
1. Create main program window
2. Create user interface components
3. Arrange components within containers
4. Implement user interaction
·
The
method: use an inheritance
mechanism
// Java 2
import javax.swing.*;
// Java 1.1
import java.awt.*;
2. Extend JFrame class (javax.swing
package) or Frame class (javax.awt
package) or other class
class FirstClass
extends JFrame {
...
}
3. Display
a window - use show() method (optionally, set windows's size
and title etc.)
Example:
import
javax.swing.*;
class FirstClass extends JFrame {
}
class startAp {
public static void
main(String[] s){
FirstClass pk = new FirstClass();
pk.setSize(200,300);
pk.show();
}
JButton b1 = new
JButton("This is a button");
b1.setText("This is the only button");
Components are being added to a container using appropriate container's methods.
JFrame objects
are collections of containers, so one needs to specify the target
container. Most frequently this will be so called "Content
Pane" of a frame. To access content pane we need to execute the
following method:
Container
cp = getContentPane();
This method returns an object cp, which is
where we place user interface components:
cp.add(b1);
Components
are being arranged within a window through so called "Layout
managers". Layout managers define rules for component placement and
their behavior upon stretching/shrinking a window. A container can be assigned with one of several different layout
managers.
By default, objects of type JFrame are assigned so called BorderLayout
whereas objects of type JPanel are assigned so called FlowLayout. To arrange components within a
container one needs to perform the following main steps:
1. set layout manager for a
container- setLayout() (or accept a default
one)
2. place components within a container using Layout
Manager add(...) method.
Component
arrangement - 5 regions N W S E C
Component placement method:
add(component_name,target_region)
Exercise
Place
5 buttons with different labels onto your GUI window - use BorderLayout.
Component
arrangement - sequential
Component placement method:
add(component_name)
Exercise
Place
3 buttons with different labels onto your GUI window - use FlowrLayout.
Component
arrangement - consecutive cells of the grid - row-wise
Component placement method:
add(component_name);
BoxLayout
Component
arrangement - sequential in either X or Y direction
Component placement method:
add(component_name);
Component arrangement - sequential in either X or Y direction
setLayout(new
BoxLayout(container_name,BoxLayout.X_AXIS));
setLayout(new
BoxLayout(container_name,BoxLayout.Y_AXIS));
Component
placement:
add(component_name);
Component aliginment
- comp.setAlignmentX(Component.CENTER_ALIGNMENT) ...
Component stretching - comp.setMaximumSize(new Dimension(x_size,
y_size)) ...
Creating gaps between
components - fixed size gaps:
add( Box.createRigidArea(new Dimension(x,y)) )
expandable gaps:
add( Box.createVerticalGlue() )
add( Box.createHorizontalGlue() )
Grid Bag Layout is the most
generic layout manager. A procedure of placing components using the Grid Bag
Layout manager is the following:
GridBagLayout gbl =
new GridBagLayout();
setLayout(gbl);
GridBagConstraints
gbc=new GridBagConstraints();
gbl.setConstraints(component_name,gbc);
add components to the application window
Absolute positioning of
components is possible when we specify "null" as a setLayout(...) command parameter. To place
components without a layout manager the following steps are needed:
add components to a conntainer
To create tabbed panes,
each containing a separate UI, use objects derived from JTabbedPane
class. Objects created with JTabbedPane class are containers (just like
panels) and are composed of several layers (panes) which mutually
overlap. Either components or containers can be added to each
tabbed pane.
To create a tabbed
pane-based interface