Java Programming I on YouTube:
https://www.youtube.com/playlist?list=PLLIqcoGpl73iaXAtS_-V_Xdx3mhTzPwb5
Which architecture is commonly used for object-oriented programs?
What is the concept of encapsulation?
Why is encapsulation important for object-oriented programming?
What is object identity?
What is object state?
A class of objects is defined by
data variables (a.k.a. attributes or fields)
constructors
Note that constructors are methods, but nothing can be returned from them
methods
accomplish tasks for which the class is responsible
can be private or public (implementation vs. public interface)
can be static just as the data variables
Defining a class does not create any objects
Java code has to be written to create objects from a user-defined class. For example,
Locomotive loco = new Locomotive(); BoxCar box = new BoxCar( 50 ); // a box car that weighs 50 ton Train freight = new Train( loco, box ); // create a train with 1 loco and 1 boxcar
The methods are not "runnable" unless some code grabs an object reference and makes a call to accomplish the required task:
Caboose servicecab = new Caboose(); // make another piece of rolling stock freight.add( servicecab ); // add caboose to the train by calling the "add" method
If class contains static fields and methods, such fields and methods do not belong to any objects.
Rather, static fields and methods belong to all objects of the class.
More so, public static fields/methods belong to the entire application -- they become global variables and methods that don't require a particular object instance to run.
A good example of a static method is the main method. main is invoked without any particular object.
Primitive data types are byte, short, int, long, char, bool, float, and double.
A data of any primitive type can be processed by the CPU commands directly. For example, CPU uses the primitive types while performing arithmetic calculations and while moving data in computer memory.
User-defined data are objects defined by a Java class. Classes can be defined in our program or elsewhere, for example, in Java library.
Consider the difference between primitive types and reference types:
When parameters are passed to a method, the method gets
copies of data -- if the parameters are of any primitive type
references to objects in memory (adresses of objects) -- if the parameters are instances of classes.
A UML diagram of a Product class might look like this:
A Java file describes the same concept using Java syntax:
public class Product { //... }
UML (Unified Modeling Language) is the industry standard used to describe the classes and objects of an object-oriented application.
The minus sign (-) in a UML class diagram marks the fields and methods that can't be accessed by other classes, while the plus sign (+) marks the fields and methods that can be accessed by other classes.
For each field, the name is given, followed by a colon, followed by the data type.
For each method, the name is given, followed by a set of parentheses. If a method requires parameters, the data type of each parameter is listed in the parentheses. Otherwise, the parentheses are left empty, and the data type of the value that's going to be returned is given after the colon.
public class Product { // the instance variables private String code; private String description; private double price; // the constructor public Product() { code = ""; description = ""; price = 0; } }
public class Product { // the instance variables private String code; private String description; private double price; // the "setter" and "getter" methods for the member variable public void setCode(String code) { this.code = code; } public String getCode() { return code; } }
import java.text.NumberFormat;
public class Product { // the instance variables private String code; private String description; private double price; // a custom method for returning user-friendly price public String getFormattedPrice() { NumberFormat currency = NumberFormat.getCurrencyInstance(); return currency.format(price); } }
A custom constructor with three parameters may look like this:
public Product(String cc, String dd, double pp) { code = cc; description = dd; price = pp; }
A better programming style might be to name the constructor parameters exactly as the class data members:
public Product(String code, String description, double price) { this.code = code; this.description = description; this.price = price; }
To disambiguate between local constructor parameters and object's member variabled the this keyword is applied in front of the data field names.
public Product(String code) { this.code = code; Product gadget = ProductDB.getProduct(code); description = gadget.getDescription(); price = gadget.getPrice(); }
The this keyword has meaning only within a class definition.
Four possible uses of the this keyword are:
// refer to an instance variable of the current object this.variableName // call another constructor of the same class this( argumentList ); // call a method of the current object this.methodName( argumentList ) // pass the current object to a method objectName.methodName( this ) // pass the current object to a static method ClassName.methodName( this )
public class Product { // the instance variables private String code; private String description; private double price; // constructors public Product() { this( "unknown", "unknown", 0.0 ); } public Product(String code, String description, double price) { this.code = code; this.description = description; this.price = price; } }
// one statement ClassName variableName = new ClassName(argumentList); // two statements ClassName variableName; variableName = new ClassName(argumentList);
For example,
Product book = new Product(); // or Product book; book = new Product(); // or String code = "ISBN:123-456-7890"; String description = "Short Novels"; double price = 5.0; Product book = new Product(code, description, price);
// A method that takes one argument and returns no values: product.setCode(productCode); // A method that takes no arguments and returns a value: double productPrice = product.getPrice(); //A method call within an expression String message = "Code: " + product.getCode() + "\n\n";
Not all things in OOP ought to be object-based.
Here is a good example of a statement that calls a static field and a static method to get the job done:
// pi times r squared: // calculate the area of a circle with a given radius. double area = Math.PI * Math.pow(radius, 2);
Any constant data is a perfect candidate to be declared both static and final. For example,
public static final int DAYS_IN_JANUARY = 31;
static fields and static methods differ from instance variables and regular methods.
Java allows a special code block to initialize the static fields:
public class className { // any field declarations private static DBConnection connection; static { // any initialization statements for static fields try { String url = "jdbc:mysql://localhost:3306/SampleDB"; String user = "robert"; String password = "secret"; connection = DBDriverManager.getConnection( url, user, password ); } catch (Exception ex) { System.err.println( "Error: unable to connect to the database." ); } } // the rest of the class }
A class can have any number of static initialization blocks
The initialization blocks can appear anywhere in the class body
All static initialization blocks are called in the order that they appear in the source code
A better alternative to the static initialization block is simply to use a static method:
public class className
{
// any field declarations
private static DBConnection connection = initializeConnection();
private static DBConnection initializeConnection() {
{
DBConnection connection = null;
try {
String url = "jdbc:mysql://localhost:3306/SampleDB";
String user = "robert";
String password = "secret";
connection = DBDriverManager.getConnection(
url, user, password
);
} catch (Exception ex) {
System.err.println(
"Error: unable to connect to the database."
);
}
return connection;
}
// the rest of the class
}
All static initialization blocks are executed before the main method.
Therefore, the instance variables (all non-static variables inside the class) are created and populated after the static variables.
What is an instance of a variable?
What is default constructor?
What is the signature of a constructor or method?
What is method overloading?