CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. • Object-Oriented Programming
Object-oriented programming (OOP) enables you to develop large-scale software and Graphical User Interfaces (GUIs) effectively. It is essentially a technology for developing reusable software. Having learned Java programming language in the previous courses, you are able to solve many computer solvable problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing GUI and large-scale software systems.
• Class and object
A class defines the properties and behaviors for objects. OOP involves programming using objects. An object represents an entity in the real world that can be distinctly identified, tangible or intangible. For example, a student, a desk, a circle, a building, a loan, or an event can all be viewed as objects. An object has a unique identity, state, and behavior, depending on how you model it based on requirements.
Copyright By PowCoder代写 加微信 powcoder
The state of an object (also known as its properties or attributes) is represented by data fields with their current values. A circle object, for example, has a data field radius, which is the property that characterizes a circle. A rectangle object, for example, has the data fields width and height, which are the properties that characterize a rectangle.
The behavior of an object (also known as its actions) is defined by methods. To invoke a method on an object is to ask the object to perform an action, which is to manipulate the data fields. For example, you may define methods named getArea() and getPerimeter() for circle objects. A circle object may invoke getArea() to return its area and getPerimeter() to return its perimeter. You may also define the setRadius(radius) method. A circle object can invoke this method to change its radius.
Objects of the same type are defined using a common class. A class is a template, blueprint, or contract that defines what an object’s data fields and methods will be. An object is an instance of a class. You can create many instances of a class and every instance has its own “state”. Creating an instance is referred to as instantiation. The terms object and instance are often interchangeable. The relationship between classes and objects is analogous to that between an apple-pie recipe and apple pies: You can make as many apple pies as you want from a single recipe.
Operations (instance methods)
Each instance of the Circle class has different states.
circle1 circle2 circle3 radius: 4 radius: 5 radius: 6
Class name
Attribute (instance variable)
CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. • Class and Object Implementation with Java
Unlike C++, Java is a pure object-oriented programming language. A Java class uses variables to define data fields and methods to define actions. In addition, a class provides methods of a special type, known as constructors, which are invoked to create a new object. A constructor can perform any actions. However, constructors are mainly designed to perform initializing actions, such as initializing the data fields of objects. It is a good software development practice to always define the data fields as “private” to better protect the data. In this case, the private data fields are only “visible” within the class, meaning the data fields can be directly accessed within the class without the instantiation of an object.
For example, the Circle class below is a template for creating circle objects (instances) with different radius values. Note that, if the Circle class doesn’t have a “main” method, it cannot be run by itself. However, a “testbed main” can be created as a driver for the purpose of unit testing the class. In other cases, the Circle class can be used by a client class, which may include a main method as the starting point of program execution.
// Circle class is a template for circle objects with different radius values.
public class Circle {
private double radius; //data are private; no direct access from outside the class
/** Default constructor; create a circle object with a default value */
public Circle() {
radius = 1.0; // set radius to the default value
/** Parameterized Constructor; create a circle object with a specified radius */
public Circle(double radius) { this.radius = radius;
/** Return the value of the radius */
public double getRadius() { return radius;
/** Set the radius of a circle object to a given value. */
public void setRadius(double radius) { this.radius = radius;
/** Compute and return the area of the circle object. */
public double getArea() {
return radius * radius * Math.PI;
/** Compute and return the perimeter of the circle object */
public double getPerimeter() { return 2 * radius * Math.PI;
//testbed main as a driver to exercise the code in this class
public static void main(String[] args) {
Circle circle1 = new Circle(4.0);
System.out.println(“The area of circle1 with radius ” + circle1.radius + ” is ”
+ circle1.getArea());
Circle circle2 = new Circle(5.0);
System.out.println(“The area of circle2 with radius ” + circle2.radius + ” is ”
+ circle2.getArea());
Circle circle3 = new Circle(6.0);
System.out.println(“The area of circle3 with radius ” + circle3.radius + ” is ”
+ circle3.getArea());
CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. Program output for test running the Circle class.
When you run a Java program, the Java runtime system invokes the main method in the main class. You can put two classes into one file, but only one class in the file can be the “public” class. The public class must have the same name as the file name. For example, the Circle class above must be stored as Circle.java since the Circle class is “public”.
Each class in the source code (.java file) is compiled into a .class file. When you compile Circle.java, a Circle.class file is generated. Note that, Java uses a combination of a compiler and an interpreter. Java programs are first compiled into bytecode, which is interpreted and run by JVM (Java Virtual Machine. Java bytecode is portable and can be run on any platform running JVM.
As another example, consider television sets. Each TV is an object with states (current channel, current volume level, and power on or off) and behaviors (change channels, adjust volume, and turn on/off). You can use a class to model TV sets. Depending on the needs of the software you are developing, you can also define a different set of attributes and associated operations for a TV object.
CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. • Constructors
A constructor is invoked to create (instantiate) an object using the “new” operator. Constructors are a special kind of method. They have three peculiarities:
1. A constructor must have the same name as the class itself.
2. Constructors do not have a return type—not even void.
3. Constructors are invoked using the “new” operator when an object is created. Constructors play
the role of initializing objects.
A constructor has exactly the same name as its defining class. Like regular methods, constructors can be overloaded (i.e., multiple constructors can have the same name but different signatures), making it easy to construct objects with different initial data values. There are 3 kinds of constructors.
1. Default constructor – no-parameter constructors.
2. Parameterized constructor – a various numbers of parameters are defined.
3. Copy constructor – to clone an object; a single parameter with the class type is defined.
Since data fields are “private” and cannot be accessed directly from outside of the class, constructors are used to construct objects. To construct an object from a class, invoke a constructor of the class using the “new” operator as follows: new ClassName(arguments); for example, new Circle() creates an object of the Circle class using the first constructor (default constructor) defined in the Circle class, and new Circle(25.0) creates an object using the second constructor (parameterized constructor) defined in the Circle class. A class normally provides a default constructor (e.g., Circle()). A class may be defined without any constructors. In this case, a public default constructor with an empty body is implicitly defined. Note that, this constructor is provided automatically ONLY if not a single constructor has been explicitly defined in the class. For example, even if a class defines a parameterized constructor without defining a default constructor, Java will NOT generate a default constructor for the class.
• Accessing Objects
An object’s data and methods can be accessed through the dot (.) operator via the object’s reference variable. Newly created objects are allocated in the memory. They can be accessed via reference variables. Objects are accessed via the object’s reference variables, which contain references to the objects. A class is essentially a programmer-defined type. A class is a reference type, which means that a variable of the class type can reference an instance of the class. You can write a single statement that combines the declaration of an object reference variable, the creation of an object, and the assigning of an object reference to the variable with the following syntax:
ClassName objectVariable = new ClassName();
An object reference variable that appears to hold an object actually contains a reference to that object. Strictly speaking, an object reference variable and an object are different, but most of the time the distinction can be ignored. Therefore, it is fine, for simplicity, to say that myCircle is a Circle object rather than use the long-winded description that myCircle is a variable that contains a reference to a Circle object.
In OOP terminology, an object’s members refer to its data fields and methods. After an object is created, its data can be accessed and its methods can be invoked using the dot operator (.), also known as the object members access operator. For example, in the Circle class, the data field radius is referred to as an instance variable because it is dependent on a specific instance. For the same reason, the
CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr. method getArea() is referred to as an instance method because you can invoke it only on a specific
instance. The object on which an instance method is invoked is called a calling object.
Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using Circle.getArea()? The answer is NO. All the methods in the Math class are static methods, which are defined using the “static” keyword. However, getArea() is an instance method, and thus non-static. It must be invoked from an object using objectVariable.methodName(arguments) (e.g., myCircle.getArea()).
Usually you create an object and assign it to a variable, then later you can use the variable to reference the object. Occasionally, an object does not need to be referenced later. In this case, you can create an object without explicitly assigning it to a variable using the syntax:
System.out.println(“Area is ” + new Circle(5.0).getArea());
The former statement creates a Circle object. The latter creates a Circle object and invokes its getArea method to return its area. An object created in this way is known as an anonymous object. The data fields can be of reference types. For example, the following Student class contains a data field name of the String type. String is a predefined Java class.
public class Student {
private String name;
private int age;
private boolean isScienceMajor; private char gender;
// name has the default value null
// age has the default value 0
// isScienceMajor has default value false // gender has default value ‘\u0000’
If a data field of a reference type does not reference any object, the data field holds a special Java value, null, which is a literal just like true and false. While true and false are Boolean literals, null is a literal for a reference type. The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and \u0000 for a char type. However, Java assigns no default value to a local variable inside a method. The following code displays the default values of the data fields name, age, isScienceMajor, and gender for a Student object. However, not assigning values to local variables and trying to print the content of the variables will cause compile errors.
CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr.
NullPointerException is a common runtime error. It occurs when you invoke a method on a reference variable with a null value. Make sure you assign an object reference to the variable before invoking the method through the reference variable.
Every variable represents a memory location that holds a value. When you declare a variable, you are telling the compiler what type of value the variable can hold. For a variable of a primitive type, the value is of the primitive type. For a variable of a reference type, the value is a reference to a memory location where an object is stored.
When you assign one variable to another, the other variable is set to the same value. For a variable of a primitive type, the real value of one variable is assigned to the other variable. For a variable of a reference type, the reference of one variable is assigned to the other variable.
CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr.
For example, in the above figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer accessible and therefore is now known as garbage. Garbage occupies memory space, so the Java runtime system detects garbage and automatically reclaims the space it occupies. This process is called garbage collection.
• Using Java library classes
One of the benefits of using Java language is the well-established Java library classes. There are many existing Java classes that can be used to solve problems without writing new classes from scratch. For example, the Date class is commonly used by many software developlers.
You can use the default constructor in the Date class to create an instance for the current date and time, the getTime() method to return the elapsed time in milliseconds since January 1, 1970, GMT, and the toString() method to return the date and time as a string. For example, the following code generates the output below.
As another example, the Random class is commonly used by software developers to generate random numbers for different purposes.
When you create a Random object, you have to specify a seed or use the default seed. A seed is a number used to initialize a random number generator. The default constructor creates a Random object using the current elapsed time as its seed. If two Random objects have the same seed, they will generate identical
CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr.
sequences of numbers. The ability to generate the same sequence of random values is useful in software testing and many other applications. In software testing, oftentimes you need to reproduce the test cases from a fixed sequence of random numbers.
You can generate random numbers using the java.security.SecureRandom class rather than the Random class. The random numbers generated from the Random are deterministic and they can be predicated by hackers. The random numbers generated from the SecureRandom class are nondeterministic and are more secure.
For a list of Java API library classes (version 14), please visit:
https://docs.oracle.com/en/java/javase/14/docs/api/index.html
• Static variables, constants and methods
A static variable is shared by all objects of the class. A static method cannot access instance members
(i.e., instance data fields and methods) of the class.
The data field radius in the circle class is known as an instance variable. An instance variable is tied to a specific instance of the class; it is not shared among objects of the same class. If you want all the instances of a class to share data, use static variables, also known as class variables. Static variables store values for the variables in a common memory space. Because of this common location, if one object changes the value of a static variable, all objects of the same class are affected. Java supports static methods as well as static variables. Static methods can be called without creating an instance of the class. To declare a static variable or define a static method, add the modifier static to the variable or method declarations.
Constants in a class are shared by all objects of the class. Thus, constants should be declared as final static. For example, the constant PI in the Math class is defined as follows:
final static double PI = 3.14159;
The main method is static as well. Static variables and methods can be accessed without creating objects. Use ClassName.methodName(arguments) to invoke a static method and ClassName.staticVariable to access a static variable. This improves readability because this makes static methods and data easy to spot.
An instance method can invoke an instance or static method and access an instance or static data field. A static method can invoke a static method and access a static data field. However, a static method of a class cannot invoke an instance method or access an instance data field without creating an object, since instance methods and instance data fields must be associated with a specific object. The relationship between static and instance members is summarized in the following table.
Instance methods Ö Ö Ö Ö Static methods X X Ö Ö
Static/or non-static
Invoke instance methods
Access instance variables
Invoke static methods
Access static variables
CS 213 Fall 2021 Note #2 – Object Oriented Programming Dr.
How do you decide whether a variable or a method should be instance or static? A variable or a method that is dependent on a specific instance of the class should be an instance variable or method. A variable or a method that is not dependent on a specific instance of the class should be a static variable or method. For example, every circle has its own radius, so the radius is dependent on a specific circle object. Therefore, radius is an instance variable of the Circle class. Since the getArea() method is dependent on a circle object’s radius value, it is also an instance method. None of the methods in the Math class, such as random, pow, sin, and cos, is dependent on a specific instance. Therefore, these methods are static methods. The main method of a class is static and can be invoked directly from a class. It is a common design error to define an instance method that should have been defined as static. For example, the method factorial(int n) should be defined as static, because it is independent of any specific instance.
• Visibility Modifiers
Visibility modifiers can be used to specify the visibility of a class and its members. You can use the “public” modifier for classes, methods, and data fields to denote that they can be accessed from any other classes. If no visibility modifier is used, then by default the classes, methods, and data fields are accessible by any class in the same package. This is known as package-private or package-access.
Packages are used to organize classes. To do so, you need to add the following line as the first non- comment and nonblank statement in the program.
package packageName;
If a class is defined without the package statement, it is said to be placed in the default package. Java
recommends that you place classes into packages rather
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com