CS代写 COMPSCI4039: Programming

COMPSCI4039: Programming

COMPSCI4039: Programming

Copyright By PowCoder代写 加微信 powcoder

At various points We’ve mentioned objects (or alluded to them)
It’s impossible to use Java without coming into contact with objects
Java is an Object Oriented Programming language (OOP)
Your wait is over…

Variables and methods
Objects make it much easier to build large complex programs
Hard for you to relate to as you haven’t built large and complex programs!
As with programming in general, there are two things to understand:
The rules and syntax for making objects [a science]
Which variables and methods to bring together [an art]
In programs we store data in variables
We keep code tidy and avoid repetition with methods
Objects allow us to:
Bring together related variables and methods into a single thing

Objects – a nice example
We’ve used a Scanner object already
It had its own internal variable(s):
E.g. it stores a copy of the String we passed it
It has lots of its own methods:
nextDouble()
nextLine()
Lots of programmers are able to use it without understanding exactly how it works (an example of encapsulation)

Objects – another example
Later in the course you’ll see how to build Graphical User Interfaces.
This code creates a window in 4 lines
People my age appreciate how remarkable that is
import javax.swing.JFrame;

public class SwingExample {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 500);
f.setVisible(true);

The code creates a JFrame object
It has attributes
defaultCloseOperation
And lots of methods
You’ll see them later

Making a class
Objects are defined by a class
We’ve already made lots
Our classes were special – they included a main method – most do not
In general classes have:
A name (starting with a capital letter)
Some variables (also known as class attributes)
Some methods
Some special methods, in particular a constructor
Each class is defined in its own specific file

Our first class

public class Person {
// Two attributes
public String name;
public int age;
// A constructor
public Person(String s,int a) {
// A method
public void sayHello() {
System.out.println(“Hi, I’m ” + name +
” and I am ” + age + ” years old.”);

Our class is called Person and will hold attributes (variables) and methods related to a person.
It has two attributes: name (String) and age (int). Note they are declared inside the class and not inside particular methods. These attributes are visible to all methods in the class.
It has a method called sayHello that prints out a message. Note how the attributes (name and age) are visible in this method.
It has a constructor. A constructor is a method that is called when an object is made. This always has the same name as the class (Person). It defines what we need to pass when we create an object from this class. Constructors don’t have a return type.

Using our class
public class Test {
public static void main(String[] args) {
// Make a person
Person personOne = new Person(“Bill”,56);
// we can call its method:
personOne.sayHello();
// we can also access its attributes
System.out.println(personOne.name);
// or set them
personOne.age = 123;
personOne.sayHello();
// We can make another now
Person personTwo = new Person(“Fred”,1);
personTwo.sayHello();

Hi, I’m Bill and I am 56 years old.
, I’m Bill and I am 123 years old.
Hi, I’m Fred and I am 1 years old.

In this example, Test and Person are in the same folder so no import command is required.
It’s the first time you’ve seen a program that consists of two classes (two files)
Note how we make Person objects
Person personOne = new Person(“Bill”,56);
Type = Person
Name = personOne
“Bill”,56 = arguments passed to constructor
We use a full stop after the name to call methods and access attributes:
personOne.sayHello();
personOne.age
You’ve seen this before!

Another example
public class Circle {
public double radius;
public Circle(double r) {
radius = r;
public double compArea() {
return 3.14152 * radius * radius;
public double compCirc() {
return 3.14152 * 2 * radius;
public void describe() {
System.out.println(“This circle has:”);
System.out.println(“\tradius ” + radius);
System.out.println(“\tarea ” + compArea());
System.out.println(“\tcircumference ” + compCirc());

public class TestCircle {
public static void main(String[] args) {
Circle c = new Circle(1.2);
Circle d = new Circle(4.56);
System.out.println(c.compArea());
d.describe();

4.523788799999999
This circle has:
radius 4.56
area 65.323510272
circumference 28.650662399999998

Making objects
We use the following syntax for making objects:
name = new (, ,…);
Compare with making primitive variables:
name; or = ;

What does public mean?
You’ve typed it a lot – what does it mean?
All classes, class attributes and class methods have a modifier that describes to which other objects they are visible
These classes, attributes, and methods are visible (and can be used by) anything
These classes, attributes, and methods can only be used by the class in which they are defined
protected:
Can be used only by other classes in the same package or that inherit from this class
More on these terms later…

public to private

public class Person {
// Two attributes
private String name;
private int age;
// A constructor
public Person(String s,int a) {
// A method
public void sayHello() {
System.out.println(“Hi, I’m ” + name +
” and I am ” + age + ” years old.”);

public class Test {
public static void main(String[] args) {
// Make a person
Person personOne = new Person(“Bill”,56);
// we can call its method:
personOne.sayHello();
// we can also access its attributes
System.out.println(personOne.name);
// or set them
personOne.age = 123;
personOne.sayHello();
// We can make another now
Person personTwo = new Person(“Fred”,1);
personTwo.sayHello();

This won’t work because the private attribute age can only be accessed within the Person class

This will work because sayHello() is a public method.

Private attributes, getters, and setters
It is convention to make attributes private
Maintains the integrity of the object (don’t allow other bits of the program to change the object any way they want)
We therefore write getter and setter methods (public) that allow other parts of the program to access and change attributes…

Person with getters and setters

public class Person {
// Two attributes
private String name; private int age;
// A constructor
public Person(String s,int a) {
public int getAge() { // getter for age
return age;
public String getName() {
return name;
public void setAge(int a) { // setter for age
public void setName(String n) {
// A method
public void sayHello() {
System.out.println(“Hi, I’m ” + name + ” and I am ” + age + ” years old.”);

Hi, I’m Bill and I am 56 years old.
Hi, I’m Bill and I am 57 years old.
public class GetSet {public static void main(String[] args) {
Person personOne = new Person(“Bill”,56);
personOne.sayHello();

personOne.setAge(57); // Bill!
personOne.sayHello();

System.out.println(personOne.getName());

Time for some questions…

Often arguments to methods (particularly constructors) will have the same name as class attributes (radius and radius)
These are different attributes!
We can use this anywhere in a class to refer to class attributes (and methods)

public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;

Where two attributes co-exist, if we don’t use this, the local one (the one passed to the method) is used.
Some programmers like to always use this when referring to class attributes (to avoid any doubt, ever).
Python uses self and you have to use it, always.
public class Circle {
private double radius = 2.0;
public Circle(double radius) {
System.out.println(radius); //3.0
System.out.println(this.radius);//2.0

public static void main(String[] args) {

What does static mean?
We’ve typed this a lot, what does it mean?
It’s an optional keyword that allows us to have class attributes and methods that can be accessed without creating an instance of the class (i.e. an object)
We used this when we introduced methods…remember this slide?…

public class Adding {

public static void addingMethod(int firstNumber, int secondNumber) {

int result = firstNumber + secondNumber;

System.out.println(firstNumber + ” + ” + secondNumber + ” = ” + result);

public static void main(String[] args) {
int a = 3;
int b = 4;
int c = 6;
int d = 21;

addingMethod(a,b);
addingMethod(c,d);
addingMethod(4,10);

Putting the method into our program
addingMethod is placed inside the { and } for the class (Adding) but not inside main
It is called by the typing its name (addingMethod) and then putting two int variables (or just int numbers) between brackets.

addingMethod was static
Notice how we called addingMethod without creating an object from the Adding class.
i.e. we never had the following:
Adding a = new Adding();
We could do this only because addingMethod has the static modifier
We can get it to work without the decorator (see next slide)

Might seem a bit odd to be making an Adding object from the main inside the Adding class. But it’s ok. Could also do it from a main in a different class.
public class Adding {
public int addingMethod(int firstNumber, int secondNumber) {
int result = firstNumber + secondNumber;
return result;
public static void main(String[] args) {
int a = 3;
int b = 4;
int c = 6;
int d = 21;

Adding addingObject = new Adding();

int aPlusb = addingObject.addingMethod(a,b);

System.out.println(a + ” + ” + b + ” = ” + aPlusb);
System.out.println(c + ” + ” + d + ” = ” + addingObject.addingMethod(c,d));

Where else have we seen static a lot?

static methods are useful
Sometimes we want access to methods without the overhead of making objects from a class
E.g. Java’s Math class has lots of useful static methods.
We don’t have to make a Math object (Math m = new Math()) to use these methods.
public class StaticExample {
public static void main(String[] args) {
double a = 3.5;
double b = Math.sqrt(a); // square root
double c = Math.cos(a);

Attributes can be static too
static attributes can be accessed without making an instance of the class.
E.g. Java’s Math class has some useful mathematical constants:
Be careful though! Static attributes take the same value for all instances of a class (all objects made from that class)
This is fine for constants like pi, but can make code unpredictable

Person with static age
public class Test {
public static void main(String[] args) {
// Make a person
Person personOne = new Person(“Bill”,56);
// we can call its method:
personOne.sayHello();
// we can also access its attributes
System.out.println(personOne.name);
// or set them
personOne.age = 123;
personOne.sayHello();
// We can make another now
Person personTwo = new Person(“Fred”,1);
personTwo.sayHello();
personOne.sayHello(); // Bill is now 1!!!

public class Person {
// Two attributes
public String name;
public static int age; // age is now static
// A constructor
public Person(String s,int a) {
// A method
public void sayHello() {
System.out.println(“Hi, I’m ” + name +
” and I am ” + age + ” years old.”);

Now age is static, if we change the age of any Person object, it changes for all of them!!

Objects and references
The following command creates two things, an object and a reference
Person personOne = new Person(“Bill”,56);
References are just like the variables we’ve seen before but now they store the address of the object they refer to.
Primitive variable, like an int
A Person object
name = Bill, age = 56

An object reference
The reference stores the address of the object it refers to (here denoted by the line)

A mental model
Think of objects as houses
The reference stores the address of the house
When we make a new house (object), we also make a variable (the reference) that stores its address.

References

Objects and scope
References follow all of the rules about scope that we’ve covered previously
Objects are available anywhere in our program (assuming that bit of the program has a reference to that object in its scope)

Each reference refers to only one object
Many references can refer to the same object…

What happens here?

public class RefFun {
public static void main(String[] args) {
Person personOne = new Person(“Bill”,56);
Person personTwo = personOne; //???

personTwo.sayHello();
personTwo.setAge(57);
personTwo.sayHello();
personOne.sayHello(); // ???

Hi, I’m Bill and I am 56 years old.
Hi, I’m Bill and I am 57 years old.
Hi, I’m Bill and I am 57 years old.

Multiple refs to the same object

public class RefFun {
public static void main(String[] args) {
Person personOne = new Person(“Bill”,56);
Person personTwo = personOne; //???

personTwo.sayHello();

personTwo.setAge(57);
personTwo.sayHello();

personOne.sayHello(); // ???

Bill, 56

(new reference, no new object)

Hi, I’m Bill and I am 57 years old.
New objects are only made where you see new

Passing objects to methods?
We don’t need to pass the objects…
…just tell the method the reference.
Recall: objects are visible everywhere as long as a reference is present
In the following example, we write a method that we pass the reference to a circle object, and it changes the circle’s radius such that the circle’s area is doubled
Note: to double a circle’s area, multiple its radius by the square root of 2

Our previous circle class with some minor changes
radius is now private
Getter and setter added
public class Circle {
private double radius;
public Circle(double r) {
radius = r;
public double getRadius() {
return radius;
public void setRadius(double r) {
radius = r;
public double compArea() {
return 3.14152 * radius * radius;
public double compCirc() {
return 3.14152 * 2 * radius;
public void describe() {
System.out.println(“This circle has:”);
System.out.println(“\tradius ” + radius);
System.out.println(“\tarea ” + compArea());
System.out.println(“\tcircumference ” + compCirc());

This circle has:
radius 3.54…
area 39.269
circumference 22.21…
doubleArea scope
main scope

public class ObjMethod {
public static void main(String[] args) {
Circle c = new Circle(2.5);
c.describe();
doubleArea(c);
c.describe();

public static void doubleArea(Circle d) {
/* a method to double the area of a circle
* To double the area, multiply the radius
* by sqrt(2)
double radius = d.getRadius();
radius *= Math.sqrt(2.0);
d.setRadius(radius);

Overloading and constructors
We saw how methods could be overloaded (same name, different arguments)
This is often useful for constructors
E.g. An ellipse has two radii (a and b):
A circle is an ellipse where a = b
So, we could make an ellipse class with two constructors:

public class Ellipse {
private double a;
private double b;
public Ellipse(double a, double b) {
this.a = a;
this.b = b;
public Ellipse(double a) { // for circles
this.a = a;
this.b = a;

Ellipse e = new Ellipse(3.0,5.0); // First constructor
Ellipse c = new Ellipse(4.0); // Second constructor

Time for some questions…

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