程序代写 ECS 140A Programming Languages

ECS 140A Programming Languages
August 10, 2022

Administrative stuff

Copyright By PowCoder代写 加微信 powcoder

HW1 has been posted and is due Sunday. Quiz 1 in class tomorrow.

Quiz time! Here’s the problem
As part of a simulation of the behavior of gas stations, you are to create a class definition called GasStation. Each object of the GasStation class keeps track of how many litres of gasoline are available at that gas station, represented as an integer. A GasStation object also has a method to simulate the dispensing of some number of litres of gasoline. That method, called dispenseGas(), reduces the amount of gasoline available at that gas station by the number of litres dispensed, assuming there are at least as many litres available as the number of litres to be dispensed. If the number of litres of gasoline to be dispensed is greater than the number of litres available, then no gasoline is dispensed. Another method, called getAvailableGas(), returns the number of litres of gasoline available at that gas station.
Every gas station object has 10,000 litres of gasoline when it is created. The dispenseGas() method always dispenses exactly 100 litres of gasoline when it is invoked.
Here’s a simple program that we might use to test your GasStation class:
public class GasStationTester
public static void main (String[] args)
GasStation chevron = new GasStation();
GasStation shell = new GasStation();
System.out.println(“Chevron has ” + chevron.getAvailableGas());
chevron.dispenseGas(); // 100 litres dispensed
chevron.dispenseGas(); // 100 more litres dispensed
System.out.println(“Chevron has ” + chevron.getAvailableGas());
System.out.println(“Shell has ” + shell.getAvailableGas());
shell.dispenseGas(); // 100 litres dispensed
System.out.println(“Shell has ” + shell.getAvailableGas());

Quiz time! Here’s the problem
And here’s the output we would expect after running this program (assuming of course that everything compiles correctly):
> javac GasStation.java
> javac GasStationTester.java
> java GasStation has 10000
Chevron has 9800
Shell has 10000
Shell has 9900

Quiz time! What¡¯s your solution?

Quiz time! Here’s a solution
public class GasStation
// instance variables go here
public int availableGas;
final public int START_AMOUNT = 10000;
final public int DISPENSE_AMOUNT = 100;
// constructor methods go here
public GasStation()
availableGas = START_AMOUNT;
// instance methods go here
public void dispenseGas()
if (availableGas >= DISPENSE_AMOUNT)
availableGas = availableGas – DISPENSE_AMOUNT;
public int getAvailableGas()
return availableGas;

Questions?

Using the while statement
public class WhileDemo {
public static void main (String[] args) {
int limit = 3; int counter = 1;
while (counter <= limit) { System.out.println("The square of " + counter + " is " + (counter * counter)); counter = counter + 1; } System.out.println("End of demonstration"); } Other loop statements public class ForDemo { public static void main (String[] args) { for (int counter = 1; counter <= 3; counter++) { System.out.println("The square of " + counter + " is " + (counter * counter)); System.out.println("End of demonstration"); } This for loop is the equivalent of the while loop on the previous slide. Visibility modifiers public class SimCoke public static void main (String[] args) System.out.println("Coke machine simulator"); CokeMachine csmachine = new CokeMachine(); CokeMachine engrmachine = new CokeMachine(); csmachine.buyCoke(); csmachine.buyCoke(); csmachine.buyCoke(); engrmachine.buyCoke(); engrmachine.buyCoke(); How can we refill an empty ? Visibility modifiers public class SimCoke public static void main (String[] args) System.out.println("Coke machine simulator"); CokeMachine csmachine = new CokeMachine(); CokeMachine engrmachine = new CokeMachine(); csmachine.buyCoke(); csmachine.buyCoke(); csmachine.buyCoke(); csmachine.numberOfCans = 12465; csmachine.buyCoke(); engrmachine.buyCoke(); engrmachine.buyCoke(); How can we refill an empty ? Does this work? Is it a good idea? Visibility modifiers public class CokeMachine public int numberOfCans; public CokeMachine() numberOfCans = 2; System.out.println("Adding another machine to your empire"); } Our problem is right up there. We¡¯re using the public visibility modifier to describe our variable numberOfCans. Variables (and methods) declared to have public visibility can be directly accessed from anywhere outside of the object created from the class. That violates the principle of encapsulation. Encapsulation is the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods. Thanks, Wikipedia. Visibility modifiers public class CokeMachine public int numberOfCans; public CokeMachine() numberOfCans = 2; System.out.println("Adding another machine to your empire"); } To prevent direct external access to the variable while still allowing the methods defined within the class to access the same variable, we change the visibility modifier to private. This will force everyone to use only the methods we define to get at that variable. From now on, we should make all our instance variables (or fields) private. The revised CokeMachine class public class CokeMachine private int numberOfCans; public CokeMachine() numberOfCans = 2; System.out.println("Adding another machine to your empire"); } public void buyCoke() if (numberOfCans > 0)
numberOfCans = numberOfCans – 1;
System.out.println(“Have a Coke”);
System.out.print(numberOfCans);
System.out.println(” cans remaining”);
System.out.println(“Sold Out”);

Parameters
public int getNumberOfCans()
return numberOfCans;
public void reloadMachine(int loadedCans)
numberOfCans = loadedCans;
parameter name
To pass a value to a method, we have to put the data type of the value and the name by which the method will refer to
the value in the parameter list.

Parameters
public int getNumberOfCans()
return numberOfCans;
public void reloadMachine(int cansOfCoke, int cansOfDietCoke) {
bin1 = cansOfCoke;
bin2 = cansOfDietCoke;
Multiple parameters are separated by commas in the parameter list.
(And this example assumes that we’ve had the foresight to declare variables called bin1 and bin2 somewhere. Of course.)

Scope of a variable
The scope of a variable (or constant) is that part of a program in which the value of that variable can be accessed. Final variables (i.e., constants)
should be defined as public, and their scope would then extend through the entire program. That¡¯s ok, because the lazy sloppy programmers can¡¯t change the value of a
final variable.

Scope of a variable
public class CokeMachine4
private int numberOfCans;
public CokeMachine4()
numberOfCans = 2;
System.out.println(“Adding another machine to your empire”); }
public int getNumberOfCans()
return numberOfCans;
public void reloadMachine(int loadedCans)
numberOfCans = loadedCans;
The numberOfCans variable is an instance variable declared inside the class but not inside a particular method, so its scope is the entire class. That is, it can be accessed by any method in the class.

Scope of a variable
public class CokeMachine4
private int numberOfCans;
public CokeMachine4()
numberOfCans = 2;
System.out.println(“Adding another machine to your empire”); }
public double getVolumeOfCoke()
double totalLitres = numberOfCans * 0.355;
return totalLitres;
public void reloadMachine(int loadedCans)
numberOfCans = loadedCans;
On the other hand, if we declare a variable within a method, it can
only be accessed from within the method. Its scope is just the method. This is a local variable; it has local scope. (Note also that variables defined in methods don’t have visibility modifiers.)

Scope of a variable
public class CokeMachine4
private int numberOfCans;
public CokeMachine4()
numberOfCans = 2;
System.out.println(“Adding another machine to your empire”); }
public int getNumberOfCans()
return numberOfCans;
public void reloadMachine(int loadedCans)
numberOfCans = loadedCans;
The scope of a parameter named in the parameter list of a method is just like that of a variable declared within that method — the parameter is also local data. It can be accessed only within that method.

Return of the s
Remember this (sort of)?
public class CokeMachine5
private int numberOfCans;
public CokeMachine5()
numberOfCans = 10;
System.out.println(“Adding another machine to your empire”); }
public int getNumberOfCans()
return numberOfCans;

Return of the s
Remember this (sort of)?
public void buyCoke()
if (numberOfCans > 0)
numberOfCans = numberOfCans – 1;
System.out.println(“Have a Coke”);
System.out.print(numberOfCans);
System.out.println(” cans remaining”);
System.out.println(“Sold Out”);

Return of the s
public class CokeMachine5
private int numberOfCans;
public CokeMachine5()
numberOfCans = 10;
System.out.println(“Adding another machine to your empire”); }
public int getNumberOfCans()
return numberOfCans;
How could we keep a running count of all the CokeMachine objects that have been created? We need a way to declare a variable that “belongs” to the class definition itself, as opposed to a variable that’s included with every instance (object) of the class.

Return of the s
public class CokeMachine5
private int numberOfCans;
public CokeMachine5()
numberOfCans = 10;
System.out.println(“Adding another machine to your empire”); }
public int getNumberOfCans()
return numberOfCans;
A variable which is shared among all instances of a class is called a static variable (sometimes it’s called a class variable).

Return of the s
public class CokeMachine5
private static int totalMachines = 0;
private int numberOfCans;
public CokeMachine5()
numberOfCans = 10;
System.out.println(“Adding another machine to your empire”); }
public int getNumberOfCans()
return numberOfCans;
A variable which is shared among all instances of a class is called a static variable (sometimes it’s called a class variable). To make one, you use the word “static” as a modifier in the variable declaration.

Return of the s
public class CokeMachine5
private static int totalMachines = 0;
private int numberOfCans;
public CokeMachine5()
numberOfCans = 10;
System.out.println(“Adding another machine to your empire”); totalMachines++;
public int getNumberOfCans()
return numberOfCans;
Updating that static variable is easy. In this case, the totalMachines variable is incremented by one every time a new CokeMachine object is constructed.

Static variables
A static variable is shared among all instances of a class. There is only one copy of a static variable for all objects of the class. Therefore, changing the value of a static variable in one object changes it for all of the others.
Memory space for a static variable is established when the class that contains it is referenced for the first time in a program.
How do you get at the value of a static variable? One way would be to use a static method.

Static methods
A static method, also known as a class method, “belongs” to the class itself, not to the objects or instances of the class. We do not have to instantiate an object of the class in order to invoke a static method of that class. With no object name to use when invoking a static method, we can use the class name.

Static methods
Here’s an example of a static method:
public class CokeMachine5
private static int totalMachines = 0;
private int numberOfCans;
public CokeMachine5()
numberOfCans = 10;
System.out.println(“Adding another machine to your empire”); totalMachines++;
public static int getTotalMachines()
return totalMachines;
public int getNumberOfCans()
return numberOfCans;

Static methods
And here’s an example of calling a static method:
public class SimCoke
public static void main (String[] args)
System.out.println(“Coke machine simulator”);
CokeMachine5 cs = new CokeMachine5();
CokeMachine5 engr = new CokeMachine5();
CokeMachine5 chem = new CokeMachine5();
CokeMachine5 library = new CokeMachine5();
System.out.println(“Total Machines = ” + CokeMachine5.getTotalMachines());
Note that CokeMachine is a class name, not an object name.

Static methods
And here’s an example of calling a static method:
public class SimCoke
public static void main (String[] args)
System.out.println(“Coke machine simulator”);
CokeMachine5 cs = new CokeMachine5();
CokeMachine5 engr = new CokeMachine5();
CokeMachine5 chem = new CokeMachine5();
CokeMachine5 library = new CokeMachine5();
System.out.println(“Total Machines = ” + CokeMachine5.getTotalMachines());
What happens when we run SimCoke?
Coke machine simulator
Adding another machine to your empire
Adding another machine to your empire
Adding another machine to your empire
Adding another machine to your empire
Total Machines = 4

Static methods
Because static methods do not operate in the context of a particular object, they cannot reference instance variables, which exist only in an instance of a class. The compiler will issue an error if a static method attempts to use a nonstatic variable. A static method can, however, reference static variables because static variables exist independent of specific objects. Instance methods can also reference static variables too.

Static methods
Now you know what all these words mean:
public class SimCoke
public static void main (String[] args)
System.out.println(“Coke machine simulator”);
CokeMachine5 cs = new CokeMachine5();
CokeMachine5 engr = new CokeMachine5();
CokeMachine5 chem = new CokeMachine5();
CokeMachine5 library = new CokeMachine5();
System.out.println(“Total Machines = ” + CokeMachine5.getTotalMachines());

Questions?

Deeper into OO programming
Up next: OO programming, principles and mechanisms for organizing hierarchies of classes
Inheritance Interfaces Polymorphism
If you don¡¯t know Java already, this will be useful. If you know Java, this will be a brief refresher.

Vending science flashback
My first generation s were limited in simulated functionality: folks could buy Cokes from the machines, but I had no way to add additional cans of Coke to the machines. That is, the simulated s had buyCoke() methods, but no loadCoke() methods.

Creating classes and objects
public class CokeMachine
private int numberOfCans;
public CokeMachine() // This is the constructor method
numberOfCans = 2;
System.out.println(“Adding another machine to your empire”); }
public void buyCoke()
if (numberOfCans > 0)
numberOfCans = numberOfCans – 1;
System.out.println(“Have a Coke”);
System.out.print(numberOfCans);
System.out.println(” cans remaining”);
System.out.println(“Sold Out”);

Vending science flashback
My first generation s were limited in simulated functionality: folks could buy Cokes from the machines, but I had no way to add additional cans of Coke to the machines. That is, the simulated s had buyCoke() methods, but no loadCoke() methods.
An evolutionary step beyond these primitive s is a class of machines that allow new cans of Coke to be
added to their inventory whenever we like. These new machines are exactly the same as their predecessors in all other respects.

Vending science flashback
My first generation s were limited in simulated functionality: folks could buy Cokes from the machines, but I had no way to add additional cans of Coke to the machines. That is, the simulated s had buyCoke() methods, but no loadCoke() methods.
An evolutionary step beyond these primitive s is a class of machines that allow new cans of Coke to be
added to their inventory whenever we like. These new machines are exactly the same as their predecessors in all other respects.
How could I create this new class of s, which
we’ll call
CokeMachine2022

One way: Make a copy of old CM…
public class CokeMachine
private int numberOfCans;
public CokeMachine()
numberOfCans = 2;
System.out.println(“Adding another machine to your empire”); }
public void buyCoke()
if (numberOfCans > 0)
numberOfCans = numberOfCans – 1;
System.out.println(“Have a Coke”);
System.out.print(numberOfCans);
System.out.println(” cans remaining”);
System.out.println(“Sold Out”);

One way: Make a copy of old CM…
public class CokeMachine2022 // give it the new name
private int numberOfCans;
public CokeMachine2022()
numberOfCans = 2;
System.out.println(“Adding another machine to your empire”); }
public void buyCoke()
if (numberOfCans > 0)
numberOfCans = numberOfCans – 1;
System.out.println(“Have a Coke”);
System.out.print(numberOfCans);
System.out.println(” cans remaining”);
System.out.println(“Sold Out”);

…then add the new method
public class CokeMachine2022 // give it the new name
private int numberOfCans;
public CokeMachine2022()
numberOfCans = 2;
System.out.println(“Adding another machine to your empire”); }
public void loadCoke(int n)
numberOfCans = numberOfCans + n;
System.out.println(“Adding ” + n + ” cans to this machine”);
public void buyCoke()
if (numberOfCans > 0)
numberOfCans = numberOfCans – 1;
System.out.println(“Have a Coke”);

What’s wrong with that?
I now have two class definitions which are almost identical. Now let’s say I have to change one because of an error in the shared code. I have to change the other.
It’s no big deal if I only have the two mostly-identical classes, but if I have lots of them, I’m making the same change over and over and over. That’s not the best use of an expensive programmer’s time.

Is there an easier way…
…to create a new and improved CokeMachine class from the old CokeMachine class without copying all the code?

Is there an easier way…
…to create a new and improved CokeMachine class from the old CokeMach

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com