Module 1 Discussions and Activity PDF
Module 1 Discussions and Activity PDF
1
The Java programming language is normally compiled to the bytecode instruction set and
binary format defined in the Java Virtual Machine (JVM) Specification (Fig. 1). Java compiler
produces intermediate code that it stores in files called class files. Those class files are then
combined with other class files and libraries to produce a complete version of the
intermediate program with everything it needs linked together. Java provides a dynamic
load feature. It loads and links the class when it refers to a class for the first time at
runtime, not compile time. JVM's class loader executes the dynamic load. Runtime Data
Areas are the memory areas assigned when the JVM program runs on the OS. The bytecode
that is assigned to the runtime data areas in the JVM via class loader is executed by the
execution engine. The execution engine reads the Java Bytecode in the unit of instruction.
Object-Oriented Programming
At the center of Java is object-oriented programming (OOP). The object-oriented
methodology is inseparable from Java, and all Java programs are, to at least some extent,
object-oriented. Because of OOP’s importance to Java, it is useful to understand OOP’s
basic principles before you write even a simple Java program. One way of understanding
OOP is to contrast it with the traditional structured programming approach encouraged by
languages such as C and Pascal. Structured languages are characterized by their support
for stand-alone subroutines, local variables, and rich control constructs. Although
structured languages are a powerful tool, even they reach their limit when a project
becomes too large. Prior to the invention of OOP, many projects were nearing the point
where the structured approach no longer works.
2
Unified Modeling Language (UML) is a graphical language for visualizing, specifying,
constructing, and documenting the artifacts of a software-intensive system. It offers a
standard way to write a system’s blueprints, including conceptual things such as business
processes and system functions as well as concrete things such as programming language
statements, database schemas, and reusable software components. It is a standardized
general-purpose modeling language in the field of object-oriented software engineering.
UML includes a set of graphic notation techniques to create visual models of
object-oriented software systems. UML combines techniques from data modeling, business
modeling, object modeling, and component modeling and can be used throughout the
software development life-cycle and across different implementation technologies.
● Static (or structural) view - emphasizes the static structure of the system using
objects, attributes, operations, and relationships.
● Dynamic (or behavioral) view - emphasizes the dynamic behavior of the system by
showing collaborations among objects and changes to the internal states of objects.
The focus in this laboratory course is with structural diagrams which emphasize the things
that must be present in the system being modeled. Since they represent the structure, they
are used extensively in documenting the software architecture of software systems.
Class Diagram
Describes the structure of a system by showing the system’s classes, their attributes, and
the relationships among the classes.
Example:
3
UML class notation is a rectangle divided into three parts: class name, attributes, and
operations. Names of abstract classes, such as Payment, are in italics. Relationships
between classes are the connecting links.
A. Association
A relationship between instances of the two classes. There is an association between two
classes if an instance of one class must know about the other in order to perform its work.
In a diagram, an association is a link connecting two classes.
B. Aggregation
An association in which one class belongs to a collection. An aggregation has a diamond
end pointing to the part containing the whole. In our diagram, Order has a collection of
OrderDetails.
C. Generalization
An inheritance link indicating one class is a superclass of the other. A generalization has a
triangle pointing to the superclass. Payment is a superclass of Cash, Check, and Credit. An
association has two ends. An end may have a role name to clarify the nature of the
association. For example, an OrderDetail is a line item of each O
rder.
4
A navigability arrow on an association shows which direction the association can be
traversed or queried. An OrderDetail can be queried about its Item, but not the other way
around. The arrow also lets you know who "owns" the association's implementation; in this
case, O
rderDetail has an I tem. Associations with no navigability arrows are bi-directional.
The multiplicity of an association end is the number of possible instances of the class
associated with a single instance of the other end. Multiplicities are single numbers or
ranges of numbers. In our example, there can be only one Customer for each Order, but a
Customer can have any number of Orders.
Multiplicities Meaning
5
Terminology
● Encapsulation - is a programming mechanism that binds together code and the
data it manipulates, and that keeps both safe from outside interference and misuse.
In an object-oriented language, code and data can be bound together in such a way
that a self-contained black box is created. Within the box are all necessary data and
code. When code and data are linked together in this fashion, an object is created.
● Inheritance - is the process by which one object can acquire the properties of
another object. Using inheritance, an object need only define those qualities that
make it unique within its class. It can inherit its general attributes from its parent.
Thus, it is the inheritance mechanism that makes it possible for one object to be a
specific instance of a more general case.
6
Main.java
7
Output:
The one shown at the top of the program is called a multiline comment. This type of
comment must begin with /* and end with */. Anything between these two comment
symbols is ignored by the compiler. As the name suggests, a multiline comment may be
several lines long.
8
definition begins with the opening curly brace ( { ) and ends with the closing curly brace ( } ).
The elements between the two braces are members of the class.
The public keyword is an access modifier. An access modifier determines how other parts
of the program can access the members of the class. When a class member is preceded by
public, then that member can be accessed by code outside the class in which it is
declared. (The opposite of public is private, which prevents a member from being used
by code defined outside of its class.) In this case, main( ) must be declared as public, since
it must be called by code outside of its class when the program is started.
The keyword static allows main( ) to be called before an object of the class has been
created. This is necessary because main( ) is called by the JVM before any objects are
made. The keyword v
oid simply tells the compiler that main( ) does not return a value.
As stated, main( ) is the method called when a Java application begins. Any information
that you need to pass to a method is received by variables specified within the set of
parentheses that follow the name of the method. These variables are called parameters. If
no parameters are required for a given method, you still need to include the empty
parentheses. In main( ) there is only one parameter, String args[ ], which declares a
parameter named args. This is an array of objects of type String. Objects of type String
store sequences of characters. In this case, args receives any command-line arguments
present when the program is executed.
The next line of code is shown here. Notice that it occurs inside main( ).
9
System.out.println("Hello LBYCPEI!");
Starter Project: h
ttps://github.com/melvincabatuan/ACMStarter_HelloWorld
Throughout the course, we will be using the ACM (Association for Computing Machinery)
Java Libraries which includes built-in Console based and Graphics based objects:
Documentation: https://cs.stanford.edu/people/eroberts/jtf/javadoc/student
10
File -> Project Structure -> Modules -> Dependencies -> ‘+’ -> JARs or dir… -> (select
acm.jar location)
acm.jar as module dependency
/*
* File: Main.java
* ---------------------
* Remember, if you change the class name, you'll need to change the filename so that it
matches.
* Then you can extend GraphicsProgram, ConsoleProgram, or DialogProgram as you like.
*/
import acm.program.*;
public class Main extends ConsoleProgram {
public void run() {
println("Hello LBYCPEI OOP!");
}
// Solves java.lang.NoClassDefFoundError
public static void main (String [] args){
(new Main()).start(args);
} }
Expected Output:
11
At this point, try to run the code. You should now see a dialog pop up similar to the one
shown in the figure below.
Say we want to create an app just like a Steam Client where users can now interact via
mouse, then what we want is a Graphical User Interface. To get started with the ACM
Graphics counterpart, we would now extend the GraphicsProgram rather than
ConsoleProgram as shown below:
/*
* File: Main.java
* ---------------------
* This class is a blank one that you can change at will. Remember, if you change
* the class name, you'll need to change the filename so that it matches.
* Then you can extend GraphicsProgram, ConsoleProgram, or DialogProgram as you like.
*/
import acm.graphics.GLabel;
import acm.program.*;
public class Main extends GraphicsProgram {
public void run() {
GLabel text = new GLabel("Hello LBYCPEI OOP!");
add(text, 100, 100);
}
// Solves java.lang.NoClassDefFoundError
public static void main (String [] args){
(new Main()).start(args);
}
}
12
After building and running the program, a dialog should pop up similar to the one shown
below. Note: that is a Label component (i.e. a text box that you can’t edit).
Laboratory Exercises:
ttps://github.com/melvincabatuan/KarelStarter
Starter Project: h
As defined in the terminology, an object stores its state in fields (variables) and exposes its
behavior through methods. In this activity, we will be exploring a simple object called Karel ‘
the Robot’.
A.) Draw the UML class diagram of Karel the Robot based on the simplified Karel.java
provided by your instructor. (Hint: Review the sample UML class diagram of
Pokemon object given in Terminology section of a Class)
13
B.) With the knowledge of Karel object attributes and behavior, solve a simple
story-problem in Karel’s world. Suppose that Karel has settled into its house, which
is the square area in the center of the following diagram:
Karel starts off in the northwest corner of its house as shown in the diagram. The
problem you need to get Karel to solve is to collect the newspaper—represented (as
all objects in Karel’s world are) by a beeper—from outside the doorway and then to
return to its initial position, facing east. (Problem taken from cs106a course in
Stanford University)(Troccoli, 2017)
Note: The laboratory instructor will provide you with the starter files and
demonstrate how to run Karel’s instructions in the world.
Thus, all you have to do is write the sequence of commands necessary to have Karel
Even though the program is short, it is still worth getting practice with
decomposition. In your solution, include a method for the first and third steps
above.
14
Draw the UML Class diagram of your final MyKarel class based on MyKarel.java in
relation to the Karel class in activity 3-A.
Set-up:
Go to Newspaper:
15
Pick Newspaper:
16
● C.) Karel has been hired to repair the damage done to the Quad in the 1989
earthquake. In particular, Karel is to repair a set of arches where some of the stones
(represented by beepers, of course) are missing from the columns supporting the
arches, as follows: (Troccoli, 2017)
• Karel starts at 1st Avenue and 1st Street, facing east, with an infinite number of beepers in
Karel’s beeper bag.
• The columns are exactly four units apart, on 1st, 5th, 9th Avenue, and so forth.
• The end of the columns is marked by a wall immediately after the final column. This wall
section appears after 13th Avenue in the above example, but your program should work
for any number of columns.
• The top of the column is marked by a wall, but Karel cannot assume that columns are
always five units high, or even that all columns are the same height.
For examples, there are several sample worlds in the starter project, and your program
17
Draw the UML Class diagram of your final StoneKarel class based on StoneKarel.java in
relation to the Karel class in activity 3-A.
● D.) In the next activity, Karel should create a checkerboard pattern of beepers
inside an empty rectangular world, as illustrated in the following before-and-after
diagram. (Karel’s final location and the final direction it is facing at the end of the run
do not matter.) (Troccoli, 2017)
Karel starts at 1st Avenue and 1st Street, facing east, with an infinite number of
beepers in its bag. The initial state of the world includes no interior walls or beepers.
Your program should put the beepers in exactly the squares shown and start
checkering by putting a beeper down on (1, 1). For example, in the picture above,
Karel has placed beepers at (1, 1), (3, 1), … (2, 2), (4, 2), etc. If you were to put
beepers on the opposite squares, such as (2, 1), (4, 1), …, (1, 2), (3, 2), etc., this would
also be a checkerboard pattern, but it would not exactly match the expectations for
this problem. In a 1x1 world, Karel should place a beeper on (1, 1).
As you think about how to solve the problem, you should make sure that your
solution works with checkerboards that are different in size from the standard 8x8
checkerboard shown in the example above. As an example, odd-sized
18
checkerboards are tricky, and you should make sure that your program generates
the following pattern in a 5x3 world:
Another special case you need to consider is that of a world which is only one
column wide or one row high. The starter folder contains several sample worlds that
test these special cases, and you should make sure that your program works for
each of them.
Draw the UML Class diagram of your final CheckerboardKarel class solution.
● E.) Program Karel to place a single beeper at the centroid of the world.
Remember that you must solve this problem using only the syntax shown in
the Karel course reader; You may not use Java variables.
Draw the UML Class diagram of your final CentroidKarel class solution.
19
2. OOP Design
● Draw the UML Class diagram of the KarelDemo application utilized in activity 1-B
which consists of Karel class, MyKarel class, and (Main class) highlighting their UML
relationships as discussed in the UML section above.
● The stanford.karel package includes a SuperKarel object that includes several new
features while retaining the basic Karel methods. The SuperKarel class includes
definitions for turnRight() and turnAround(). The SuperKarel implementations of
these methods tie into the internal workings of Karel to implement these operations
more efficiently. If you use turnRight() in a SuperKarel subclass, your program will
make an immediate right turn and not go through the process of turning left three
times. Given the stated information, draw the UML Class diagram of SuperKarel in
relation to Karel utilizing the Object-Oriented design approach.
● The SuperKarel class allows Karel to paint the corner on which it is standing using
the instruction:
paintCorner(color);
The value enclosed in the parentheses—which is called an argument in the
terminology of programming languages—may be any of the following:
The null color value indicates that a corner has no color, which means that the little
cross in the center shows through. When you create a new Karel world, all corners
initially have null as their color.
Repeat exercise 1-D, but instead of creating a checkerboard pattern of beepers,
make a checkerboard pattern of green boxes using the method:
paintCorner(color)
20
Draw the UML Class diagram of this application which consists of Karel class,
SuperKarel class, MyKarel class, and Main class highlighting their UML relationships
as discussed in the UML section above.
References:
● Gosling, J., Joy, B., Steele, G., Bracha, G., & Buckley, A. (2015). T he Java language
specification. Oracle America, Inc.
● Roberts, E. (2005). Karel the robot learns java. Department of Computer Science
Stanford University.
● Roberts, E. (2008). The Art & Science of Java. Pearson.
● Oracle. Java Documentation. ( https://docs.oracle.com/en/java )
● Schildt, H. (2017). Java: A Beginner's Guide, 7th Edition. McGraw-Hill Education.
● Troccoli, N. (2017). CS 106A: Assignment #1: Karel the Robot. Stanford University
● UML basics: The component diagram.
http://www.ibm.com/developerworks/rational/library/dec04/bell/
21
Appendix:
22