An object exists in memory and performs a specific task
Class: Code that describes a particular type of object.
Remember:
- Data is stored immediately within the variable (memory location) in primitive variables.
- A pointer to another memory location is stored in reference variables.
Creating a Typical Object:
Random rand= new Random();Suppose we want a Rectangle object to store length and width (fields)
setLength, setWidth, getLength, getWidth, getAreaUnified Modeling Language (UML): Set of standard diagrams for graphically depicting object-oriented systems.
+ and - determine private and public dataGeneral Structure:
For our Rectangle example:
Access Specifier: Java keyword that indicates how a field or method can be accessed.
public: Can be accessed by code outside of class.private: Can only be accessed by method that are members of the same class.public class Rectangle
{
// These variables can only be accessed by methods in the class
private double length;
private double width;
// == Mutators ==
// Note how this isn't static b/c we want each instance to have their own setLength method
// - We only use static for methods that don't depend on specific instances
public void setLength (double l) {
length = l;
}
public void setWidth (double w) {
width = w;
}
// == Accessors ==
public double getLength () {
return length;
}
public double getWidth () {
return width;
}
// == Other ==
public double getArea()
{
return length * width;
}
}Because of data hiding, we interact with fields with:
Note: Important concept in OOP!
Data that requires calculation has the potential to become stale.
double area = length * width v.s. public getArea() { return length * width })Common layout:
Instance Methods: Methods that are not declared with the static keyword.
Instance Fields: Fields that each instanced object has their own version of.
Note: Both require an object to be created to be used!
Suppose the following setter:
public Rectangle(double l, double w) {
length = l;
width = w;
}We can use the this keyword to refer to instance fields with the same names as the arguments:
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}Constructor: Method that’s automatically called when an object is created.
void)Constructors don’t have their return type listed.
For our Rectangle example:
We can create reference variables without initializing them.
e.g.,
Rectangle box;If you try to use an uninitialized local reference variable a compiler error will occur.
If you don’t write a constructor, Java will provide a default constructor that:
boolean fields to false.null.Note: The default constructor exists only when you don’t write a constructor and takes no parameters.
No-Arg Constructor: A constructor that doesn’t accept arguments.
Note: A No-Arg constructor \ne the default constructor.
When passing an argument, the object;s memory address is what’s actually passed into the parameter variable.
Method Overloading: When two or more methods have the same name but different argument lists.
e.g.,
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public Rectangle() {
this.length = 7;
this.width = 7;
}Method Signature:
add(int,string) \ne add(string,int))For example, here are the method signatures of the Rectangle examples in the previous section:
Rectangle(double,double)
Rectangle()Binding: The process of bathing a method call with the correct method
BankAccount ExampleHere’s a class that demonstrates overloaded methods and constructors.
Variables declared as instance fields can be accessed by any instance method in the same class as the field.
public access specifier, it can also be accessed by code outside the class, which should be avoided because it goes against data hiding.A parameter variable, in effect, is a local variable.
this is discouraged.import StatementsPackage: Group of related classes.
import statements, like so: import java.util.Scanner; import java.util.*;java.lang package is automatically made available to any Java class (e.g., System, String)java.io: Input/outputjava.lang: Java languagejava.net: Network communicationsjava.security: Securityjava.sql: SQL databasesjava.text: Formatting textjava.util: Various utility classes (e.g., Scanner, random)toString MethodRectangle box = new Rectangle();
// Explicitly calling toString()
System.out.println(box1.toString());
// Implicitly calling toString()
System.out.println(box1);toString can also be called implicitly whenever you concatenate the object with a string (e.g., "The rectangle data is: " + box1)toString method will return class name and hash of memory address of the object.Static fields and static methods don’t belong to a single instance of a class.
To invoke a static method or field, the class name is used instead of an instance name, like so:
// Class Name: Math
// Static Method: sqrt()
double x = Math.sqrt(25.0);To declare a static field, put static keyword between access specifier (private/public) and field type (e.g., int, double), like so:
private static int instanceCount = 0;Static methods can be declared by putting static between access specifier and return type, like so:
public static double milesToKilos(double miles)Math, Java Standard Library) and have no need to collect and store data.equals MethodLike toString, all objects have a default equals method that compares memory addresses of the objects like the == operator.
equals doesn’t compare the contents of objects (you can implement it yourself, though)Two ways to copy an object:
// Reference-Only Copy
Stock company1 = new Stock("XYZ", 9.62);
Stock company2 = company1;A constructor that accepts an existing object of the same class and clones it.
Example:
// Copy Constructor
public Stock(Stock orig)
{
this.symbol = orig.getSymbol();
this.sharePrice = orig.getSharePrice();
}// Deep Copy
Stock company1 = new Stock("XYZ", 9.62);
Stock company2 = new Stock(company1):Null Reference: Reference variable that points to nothing.
if (x != nul) { /* (do something with x) */ }this Referencethis Reference: Name an object can use to refer to itself.
this must be the first statement in the constructor.Unused objects should be destroyed to free the memory they consumed.
null for Java to garbage collect it.null.finalize MethodIf an object has a method with the signature—
public void finalize()—It will run prior to the garbage collector reclaiming its memory.
- Remember that we can’t tell when finalize will actually be run, because the garbage collector is a background thread that runs periodically.
Object Aggregation: Making an instance of one class a field in another class.
Example UML Diagram: