Comp 524-Programming Languages
2-5 Overview-JAVA
Instructor: (FB 150,
Copyright By PowCoder代写 加微信 powcoder
Common Overview Example
write(‘Hello, World!’), nl.
“Hello World”;
echo “hello world”
(format t “Hello, World!~%”)
#include
int main() {
printf(“Hello, World!\n”);
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World”);
Procedural Java: I/O and Main
import java.util.Scanner;
public class PassUtil {
static Scanner scanner = new Scanner(System.in);
public static double inputDouble(String aPrompt) {
System.out.println(aPrompt);
return scanner.nextDouble();
public static void main (String[] args) {
for (;;) {
double totalScore = inputDouble(“Please input the total score”);
if (totalScore < 0) {
double finalScore = inputDouble("Please input the final score");
System.out.println(String.format("isPass:%s", pass(totalScore, finalScore) ? "true" : "false"));
Procedural Java: Logic
public static final int PASS_CUT_OFF = 60;
public static boolean regularPass(double totalScore) {
return totalScore >= PASS_CUT_OFF;
public static final int HIGH_FINAL_CUTOFF = 40;
public static final int HIGH_FINAL_THRESHOLD = 80;
public static boolean highFinalPass(
double totalScore, double finalScore) {
return (finalScore >= HIGH_FINAL_THRESHOLD) &&
(totalScore >= HIGH_FINAL_CUTOFF);
public static boolean pass (double totalScore, double finalScore) {
return regularPass(totalScore) || highFinalPass(totalScore, finalScore);
Good use of Java?
Declarative vs Non-Declarative: Possible Interpretation
fun regularPass aTotal = aTotal >= 60;
val PASS_CUTOFF = 60;
fun regularPass aTotal = aTotal >= PASS_CUTOFF;
const double PASS_CUT_OFF = 60;
_Bool regularPass(double totalScore) {
return totalScore >= PASS_CUT_OFF;
Declared vs Inferred.
Declarative vs Procedural: Complementing
Declarative: Specify what we want
Procedural : Implement what we want
floats[] floats = {4.8f, 5.2f, 4.5f};
public static float sum(Float[] aList) {
float retVal = (float) 0.0;
for (int i = 0; i < aList.length; i++) {
retVal += aList[i];
return retVal;
Type declaration
Imperative, Functional, O-O, …
Pure declarative system replacing procedural system?
Procedural vs. Declarative vs Languages (Review)
(FSA) Finite State Automata
Regular Expressions
(PDA) Push Down Automata
Context Free Grammars
(LBA) Linear Bounded Automata
Context Sensitive Grammars
Turing Machines/Java/C/Lisp/ML
Regular Languages
Context Free Languages
Context Sensitive Languages
Recursively enumerable Languages
Logic Programming
Prolog (Review)
passCutoff(60).
regularPass(Total) :- passCutoff(PassCutoff), Total >= PassCutoff.
highFinalCutoff(40).
highFinalThreshold(80).
highFinalPass(Total, Final) :- highFinalThreshold(HighFinalThreshold),
Final >= HighFinalThreshold,
highFinalCutoff(HighFinalCutoff),
Total >= HighFinalCutoff.
pass(Total, Final) :- regularPass(Total).
pass(Total, Final) :- highFinalPass(Total,Final).
:-pass(59, 79).
:-pass(59, 80).
:-pass(59, 0).
Oder of rules and operands of and/or should only affect performance and not correctness
In procedural languages, a single alternative for a function call is chosen at compile time based on its signature
In Prolog, all are definitions of a rule tried until one can be derived from the facts
Common Overview Example (Review)
write(‘Hello, World!’), nl.
“Hello World”;
echo “hello world”
(format t “Hello, World!~%”)
#include
int main() {
printf(“Hello, World!\n”);
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World”);
Procedural Java: I/O and Main (Review)
import java.util.Scanner;
public class PassUtil {
static Scanner scanner = new Scanner(System.in);
public static double inputDouble(String aPrompt) {
System.out.println(aPrompt);
return scanner.nextDouble();
public static void main (String[] args) {
for (;;) {
double totalScore = inputDouble(“Please input the total score”);
if (totalScore < 0) {
double finalScore = inputDouble("Please input the final score");
System.out.println(String.format("isPass:%s", pass(totalScore, finalScore) ? "true" : "false"));
Procedural Java: Logic (Review)
public static final int PASS_CUT_OFF = 60;
public static boolean regularPass(double totalScore) {
return totalScore >= PASS_CUT_OFF;
public static final int HIGH_FINAL_CUTOFF = 40;
public static final int HIGH_FINAL_THRESHOLD = 80;
public static boolean highFinalPass(
double totalScore, double finalScore) {
return (finalScore >= HIGH_FINAL_THRESHOLD) &&
(totalScore >= HIGH_FINAL_CUTOFF);
public static boolean pass (double totalScore, double finalScore) {
return regularPass(totalScore) || highFinalPass(totalScore, finalScore);
Good use of Java?
Classes as Modules
Class (File)
Global (Static) Declaration
Local Declaration
Classes are modules that put walls around the methods and global variables in a program
These walls make only certain methods and variables visible outside
Program(ming language) with modules called modular (Modula, Modula-2, Mesa)
Modular Java
import java.util.Scanner;
public class PassUtil {
static Scanner scanner = new Scanner(System.in);
public static double inputDouble(String aPrompt) {
System.out.println(aPrompt);
return scanner.nextDouble();
public static final int PASS_CUT_OFF = 60;
public static boolean regularPass(double totalScore) {
return totalScore >= PASS_CUT_OFF;
public static final int HIGH_FINAL_CUTOFF = 40;
public static final int HIGH_FINAL_THRESHOLD = 80;
public static boolean highFinalPass(
double totalScore, double finalScore) {
return (finalScore >= HIGH_FINAL_THRESHOLD) &&
(totalScore >= HIGH_FINAL_CUTOFF);
public static boolean pass (double totalScore, double finalScore) {
return regularPass(totalScore) || highFinalPass(totalScore, finalScore);
public class ModularPassMain {
public static void main (String[] args) {
for (;;) {
double totalScore = PassUtil.inputDouble
(“Please input the total score”);
if (totalScore < 0) {
double finalScore = PassUtil.inputDouble(
"Please input the final score");
System.out.println(String.format("isPass:%s",
PassUtil.pass(totalScore, finalScore)
? "true" : "false"));
Static variables allocated memory once when containing class loaded and occupy space until end of process
Instance variables allocated space each time class instantiated
Classes as Types
Class (File)
Global (Static) Declaration
Local Declaration
Classes are ways for programmers to define their own types
Values of these types are created by instantiating the classes and share the behavior defined by the type. These values have copies of the dynamic/instance variables defined by the class
A class is a template or blue print for generating instances
Program(ming language) with instantiatable classes called object-based (Simula-67)
Double Role of Class
Classes are modules that puts walls around the methods and variables in a program
These walls make only certain methods and variables visible outside
Classes are ways for programmers to define their own types
Values of these types are created by instantiating the classes
Conflicting/competing or complementary roles supporting each other?
Program Objects~ Physical Objects
Natural Objects
Manufactured Objects
~ Program Components – have a well-defined creator
Factory Analogy For Both Roles
Operations
accelerate
instance of
Instance Methods
getFactorial()
Factory Operations
Class (static) Methods
Since class can be active, more like a factory than a blue print.
numInstances ()
Factory-metaphor != factory pattern.
Class (instance) method: method invoked on class (class instance)
manufactured by
ModularObject-Based?
import java.util.Scanner;
public class PassUtil {
static Scanner scanner = new Scanner(System.in);
public static double inputDouble(String aPrompt) {
System.out.println(aPrompt);
return scanner.nextDouble();
public static final int PASS_CUT_OFF = 60;
public static boolean regularPass(double totalScore) {
return totalScore >= PASS_CUT_OFF;
public static final int HIGH_FINAL_CUTOFF = 40;
public static final int HIGH_FINAL_THRESHOLD = 80;
public static boolean highFinalPass(
double totalScore, double finalScore) {
return (finalScore >= HIGH_FINAL_THRESHOLD) &&
(totalScore >= HIGH_FINAL_CUTOFF);
public static boolean pass (double totalScore, double finalScore) {
return regularPass(totalScore) || highFinalPass(totalScore, finalScore);
public class ModularPassMain {
public static void main (String[] args) {
for (;;) {
double totalScore = PassUtil.inputDouble
(“Please input the total score”);
if (totalScore < 0) {
double finalScore = PassUtil.inputDouble(
"Please input the final score");
System.out.println(String.format("isPass:%s",
PassUtil.pass(totalScore, finalScore)
? "true" : "false"));
Common design pattern for interactive programs?
public static final int PASS_CUT_OFF = 60;
public static boolean regularPass(double totalScore) {
return totalScore >= PASS_CUT_OFF;
public static final int HIGH_FINAL_CUTOFF = 40;
public static final int HIGH_FINAL_THRESHOLD = 80;
public static boolean highFinalPass(
double totalScore, double finalScore) {
return (finalScore >= HIGH_FINAL_THRESHOLD) &&
(totalScore >= HIGH_FINAL_CUTOFF);
public static boolean pass (double totalScore, double finalScore) {
return regularPass(totalScore) || highFinalPass(totalScore, finalScore);
I/O and Main
static Scanner scanner = new Scanner(System.in);
public static double inputDouble(String aPrompt) {
System.out.println(aPrompt);
return scanner.nextDouble();
public static void main (String[] args) {
for (;;) {
double totalScore = inputDouble(“Please input the total score”);
if (totalScore < 0) {
double finalScore = inputDouble("Please input the final score");
System.out.println(String.format("isPass:%s", pass(totalScore, finalScore) ? "true" : "false"));
(Smalltalk) MVC and Observer Pattern
Controller 1 (Input)
Controller 2
Controller 3
Controller 4
Changed model notifies views
Observable
Model (Logic)
View 1 (Output)
Observers/Views can have different implementations not known to Observables/Models
A Tale of Two MVCs: Web MVC
Model (Logic)
Controller 1
Controller 2
Controller 3
Controller 4
In Http-based “MVC” a single view and controller exist in the browser and the model in the server. A Model cannot initiate actions in the browser so the controller directly communicates with the view
Observables/Models call notification methods in Observes/Views
Observers/Views can have different implementations not known to Observables/Models
How to make sure method calls are bound to different implementations dynamically (at runtime)
Dynamic Dispatch
Additional construct seen in Java?
Concrete superclass defines these methods, subclass overrides chosen at runtime (e.g. Common Observable, Observer class in Smalltalk): C++ term of virtual methods
C++ supported also abstract classes.
Interfaces (Mesa)!
Real-World Analogy for Interfaces
Specification
implements
implements
manufactured
manufactured
Interface Uses
Dynamic dispatch (like superclasses)
Specification/documentation of classes
Allows an implementation to be replacement to be easily replaced (Regular grade model with flexible fudging grade model)
Allows a single call to refer to multiple implementations (Grade model notifying console and GUI views)
Implementation Replacement
Captures commonality of regular and flexible grade model
Interfaces
Define contracts between our users and implementers
Optional – they may not be used
Good style to use them
Each instance method must be in some interface (static methods cannot be in interfaces in Java but in Mess and previous languages separating specification and implementation)
Each object variable must be typed by an interface
Model Interface
package pass.model;
import java.beans.PropertyChangeListener;
public interface PassModel {
public static final String FINAL_SCORE = "finalScore";
public static final String TOTAL_SCORE = "totalScore";
public static final String PASS = "pass";
Double getTotalScore();
Double getFinalScore();
Boolean isPass();
void setScores(Double aTotalScore, Double aFinalScore);
void addPropertyChangeListener(PropertyChangeListener aListener);
A Java observer interface, well documented
Abstract Model Class
package pass.model;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public abstract class AnAbstractPassModel implements PassModel {
Double totalScore;
Double finalScore;
Boolean pass;
PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener aListener) {
propertyChangeSupport.addPropertyChangeListener(aListener);
public Double getTotalScore() {
return totalScore;
public Double getFinalScore() {
return finalScore;
A Java helper class for obseverables, well documented
Abstract Model Class
public void setScores(Double aTotalScore, Double aFinalScore) {
Double oldTotalScore = totalScore;
Double oldFinalScore = finalScore;
Boolean oldPass = pass;
totalScore = aTotalScore;
finalScore = aFinalScore;
pass = isPass();
propertyChangeSupport.firePropertyChange(TOTAL_SCORE,
oldTotalScore, totalScore);
propertyChangeSupport.firePropertyChange(FINAL_SCORE,
oldFinalScore, finalScore);
propertyChangeSupport.firePropertyChange(PASS,
oldPass, pass);
resetProperties();
* Values have been consumed, reset them for the next setScore
protected void resetProperties() {
totalScore = null;
finalScore = null;
pass = null;
Property not fired if oldValue == newValue
SubClass1: Regular Model
package pass.regular;
import pass.PassUtil;
import pass.model.AnAbstractPassModel;
public class ARegularPassModel extends AnAbstractPassModel{
public Boolean isPass() {
return PassUtil.regularPass(getTotalScore());
SubClass2: (Flexible) Model Class
package pass.highFinal;
import pass.PassUtil;
import pass.model.AnAbstractPassModel;
public class APassModel extends AnAbstractPassModel{
public Boolean isPass() {
return PassUtil.pass(getTotalScore(), getFinalScore());
How to choose between different implementations of an interface (PassModel)
Singletons and Factories
Factory Class/Object for class C
Provides a static or instance method to return an object of some class bound (after possibly instantiating it) to the factory
Singleton class
A class with only one instance
A factory for that class would always return that instance and can be used to enforce singletons.
Used for singletons and selecting some implementation of an interface
Model Factory
package pass.model;
import pass.regular.ARegularPassModel;
public class PassModelFactory {
static PassModel passModel;
public static PassModel getPassModel() {
if (passModel == null) {
passModel = new ARegularPassModel();
return passModel;
public static void setPassModel(PassModel newVal) {
passModel = newVal;
View/Observer Interface & Class
package pass.view;
import java.beans.PropertyChangeListener;
public interface PassView extends PropertyChangeListener {
package pass.view;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import pass.model.PassModel;
public class AConsolePassView implements PassView {
public void propertyChange(PropertyChangeEvent evt) {
if (PassModel.PASS == evt.getPropertyName()) {
Boolean aPass = (Boolean) evt.getNewValue();
System.out.println(String.format("isPass:%s",
aPass ? "true" : "false"));
Called when new score is set by model
No added methods now, may change mind
package pass.view;
import pass.regular.ARegularPassModel;
public class PassViewFactory {
static PassView passView;
public static PassView getPassView() {
if (passView == null) {
passView = new AConsolePassView();
return passView;
public static void setPassView(PassView newVal) {
passView = newVal;
Controller Interface/Class
package pass.controller;
public interface PassController {
void processInput();
package pass.controller;
import pass.PassUtil;
import pass.model.PassModelFactory;
public class AConsolePassController implements PassController {
public void processInput() {
for (;;) {
double aTotalScore = PassUtil.inputDouble
("Please input the total score");
if (aTotalScore < 0) {
double aFinalScore = PassUtil.inputDouble
("Please input the final score");
PassModelFactory.getPassModel().setScores(aTotalScore, aFinalScore);
No output, delegates computation to the model.
Controller Factory
package pass.controller;
public class PassControllerFactory {
static PassController passController;
public static PassController getPassController() {
if (passController == null) {
passController = new AConsolePassController();
return passController;
public static void setPassController(PassController newVal) {
passController = newVal;
package pass.model;
import pass.controller.PassControllerFactory;
import pass.view.PassViewFactory;
public class MVCPassUtil {
public static void startPassMVC () {
PassModelFactory.getPassModel().
addPropertyChangeListener(PassViewFactory.getPassView());
PassControllerFactory.getPassController().processInput();
Main Class: (Flexible) Pass Model
package pass.highFinal;
public class PassMain {
public static void main (String[] args) {
PassModelFactory.setPassModel(new ARegularPassModel());
MVCPassUtil.startPassMVC();
Main Class: (Flexible) Pass Model
package pass.regular;
import pass.model.PassModelFactory;
public class RegularPassMain {
public static void main (String[] args) {
PassModelFactory.setPassModel(new APassModel());
MVCPassUtil.startPassMVC();
Common Overview Example
write('Hello, World!'), nl.
"Hello World";
echo “hello world”
(format t "Hello, World!~%")
#include
int main() {
printf(“Hello, World!\n”);
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World”);
Beyond these languages?
Common Overview Example
write(‘Hello, World!’), nl.
“Hello World”;
echo “hello world”
(format t “Hello, World!~%”)
#include
int main() {
printf(“Hello, World!\n”);
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World”);
Beyond these languages?
Double Role of Class (Review)
Classes are modules that puts walls around the methods and variables in a program
These walls make only certain methods and variables visible outside
Classes are ways for programmers to define their own types
Values of these types are created by instantiating the classes
Unifying concept– classes have acesss-controlled static variables and methods and their instances have access-controlled dynamically allocated variables and methods
Dynamically alloc