An Introduction to Classes
with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
private
public
getter methods
(that allow external code to "see" the contents of
attributes) where neededpublic
setter methods
(that allow external code to "determine" the contents of
attributes) where needed
private
(and final
if appropriate)public
and final
access
class
class-name
{
public class Purchase { // Instance Attributes private int productCode, quantity; private double price; // Constructor public Purchase(int code, int q, double p) { productCode = code; quantity = q; price = p; } // Getters public double getPrice() { return price; } public int getProductCode() { return productCode; } public int getQuantity() { return quantity; } // Setters public void setPrice(double p) { price = p; } public void setQuantity(int q) { quantity = q; } }
this.
can be used to disambiguate attributes
and formal parameters (and local variables) with the
same name__init__()
method_
is a strong suggestion
to not access it from outside)public static void
method
named main()
that is passed
a String[]
main()
is static so that an object doesn't
have to be created in order to invoke itmain()
is passed a String[]
so
that the user can provide information (called command-line
arguments or run argumens) to the program at start-upmain()
method with the approrpiate signatuemain()
and, perhaps, private static
helper methods)