CLASSES AND OBJECTS

Summer 2019 OBJECT BASICS

• Everything in Java is part of a class • This includes all methods (functions) • Even the main() method is part of a class • Classes are declared similar to C++ • This includes the ability to categorize members as public or private, but the qualifiers are placed before each individual member • With no access level, a class member is considered package-private (accessible only to other classes in the same package, a concept discussed later) • These two categories have the same meaning as in C++: public means accessible from anywhere, private means only accessible from within the class • Follow the same guidelines as in C++ (member data usually private, member functions at an appropriate level based on access requirements) OBJECT BASICS

• Class Declaration, continued • In Java, classes themselves have access levels. • Normal classes are usually declared public, so they can be accessed anywhere • Other access levels are usually reserved for specific types of classes (such as inner classes, discussed later) • Circle.java – class declaration example CREATING OBJECTS

• Objects are created from a class using the new operator and they must be attached to a reference variable. This takes two steps: 1. Declare the object reference variable 2. Create the object with new and attach it to the reference variable • This means every object is dynamically created. CREATING OBJECTS

• The Format: ClassName objectReference; objectReference = new ClassName(); OR ClassName objectReference = new ClassName(); • Examples: Circle myCircle; //Circle is a class myCircle = new Circle();

Dog fido = new Dog(); //Dog is a class NULL

• When you create a reference variable and do not give it a value, it actually has a value of null • null does not have a true type • You can assign null to any reference variable • You may not assign null to any primitive type • If you attempt to access a non- method (or data) on a reference variable with the value of null, Java will throw a NullPointerException and your program will crash at run-time (but it will compile fine) • Therefore, if you are ever in a situation where your reference variable may have not been initialized, you should check it against the value of null (using either == or != as appropriate) if (obj != null) //Do something with obj REFERENCE VARIABLES

• Be careful! Since the name used to refer to an object is a reference and not the object itself, assignments are just on the reference, like with C++ pointers. So, for example: Circle c1 = new Circle(); Circle c2 = new Circle();

c1 = c2; • This last statement does not copy circle c2 into c1. Instead, it just copies the reference, so both reference variables are now referring to the same object (c2). USING OBJECTS

• With a created object, you can access the object’s methods and data with the dot- operator. • Format: objectReference.data objectReference.method(arguments) • Example: Circle c1 = new Circle(); c1.radius = 10; //Sets radius to 10

//Compute and print the area with the findArea method System.out.print(“Area = ” + c1.findArea()); CONSTRUCTORS

• Similar to C++ • Same name as the class • No return type • Can have multiple constructors (function overloading is allowed) • Primary purpose is generally to handle object initialization • If not defined, empty default constructor is automatically defined (no parameters)

• A constructor is invoked when creating an object with the new operator: c1 = new Circle(); //Default constructor c2 = new Circle(10.0); //Constructor with one parameter OBJECTS AS PARAMETERS

• Remember, the name we use is a reference variable, the actual objects are created with the new operator • So, when passed into a method, the reference variable is copied (just like with arrays), not the object. The method parameter becomes a reference to the original object. This is still technically pass-by-value. • The method has access to the original object. Changes inside the method will affect the original. • However, the assignment operator just changes which object the reference variable is pointing at within the function, it will not change what the original reference variable is referring to. STATIC VS. INSTANCE VARIABLES AND METHODS

The modifier static can be used on variables and on methods • Variables • A static variable is shared by all instances of a class. Only one variable is created for the entire class • For an Instance variable (not static) each object gets its own copy • Methods • An instance (non-static) method can only be called by an object • A static method (or class method) can be called without creating instances of a class. Can be called through the class name or object name (best practice is to call through the class name as a reminder that it is static) • Access • Static variables can be accessed from both instance methods or static methods • Instance variables can not be accessed from static methods. • To make a class variable constant, add the keyword final as a modifier on the declaration. • Generally, you want these also static, it is more efficient to have one variable shared by the whole class STATIC VS. INSTANCE EXAMPLE class Student { private int testGrade; // instance variable (non-static) // static variable (class variable) private static int numStudents = 0; private final static int pointsPossible = 100; // class constant public Student() { testGrade = 0; } public void setGrade(int gr) { testGrade = gr; } public int getGrade() { return testGrade; } public static void incrementNumStudents() { numStudents++; } public static int getNumStudents() { return numStudents; } } STATIC VS. INSTANCE CONTINUED

• In the previous example: • testGrade is an instance variable, each object will have its own copy • numStudents is a static class variable, so there is only one shared by the whole class • pointsPossible is a class constant, there is only one variable and its value cannot be changed • setGrade and getGrade are instance methods, must be called by individual objects • incrementNumStudents and getNumStudents are static methods, they cannot access instance variables and can be called through the class name, regardless of whether any objects have been created • Student.java – A copy of this code example, with a small main program that shows some calls THE KEYWORD this

• In C++, this is a pointer to the current calling object. The same keyword exists in Java, but has two uses. • In Java, this is a reference variable to the current calling object • Very similar, but slightly different in practice • Like in C++, it is optional (and somewhat redundant) in most instances when used this way. The only time this usage is required is when variables are being shadowed (such as when a parameter has the same name as a piece of member data) THE KEYWORD this

• In Java, this can also be used to call one constructor from another in class. • Use it like the function name in the call • Example: public Date(int m, int d, int y) //3-parameter constructor { month = m; day = d; year = y; }

public Date(int m, int d) //2-parameter constructor { this(m,d,0); //calls 3-param constructor } FRACTION CLASS

• In COP 3330, you may have seen a Fraction class example. This is the corresponding Fraction class in Java • Fraction.Java ARRAYS OF OBJECTS

• Creating an array of objects is a little trickier than an array of a primitive type • Similar to creating an array of pointers in C++ 1. Create an array using the same syntax as primitive types, using the class name instead of the primitive type name Student[] list = new Student[10]; This creates an array of reference variables 2. Create the individual objects with new and attach to the reference variables. This can be done separately: list[0] = new Student(); list[1] = new Student(); Or with a loop (as long as you are using the same constructor for each object): for (int i = 0; i < list.length; i++) list[i] = new Student(); ENUMS

• An enum (enumerated) type is a special type that only allows a variable to be set to certain predefined constants • You define an enum like a class, but using the enum keyword, then inside of the enum, you specify the available constants in a comma-separated list: public enum enumName { CONSTNAME1, CONSTNAME2, CONSTNAME3; } • Unlike many other languages, Java enums can have methods and member data • These are defined like in any other class ENUMS

• Enums all have certain methods predefined • For example, values() returns an array containing all of the possible values of an enum in the order they are declared • There is a special method called compareTo() that is defined in enums (and many other classes), which compares the values of two variables of a specific enum type, treating them as if they are defined from smallest to largest (in previous example, CONSTNAME1 is less than CONSTNAME2, for example). We will discuss general usage of this method in more detail later. • Technically, all enums inherit from Java.lang.Enum, so they cannot inherit from any other class ENUMS

• You CAN define constructors for enums, which you can pass values to when declaring the value constants. Example: public enum testEnum{ VALUE1(1, 2.5), VALUE2(2, 3.5), VALUE3(3, 4.5); private int x; private double y; public testEnum(int xArg, double yArg) { x = xArg; y = yArg; } } • Example of an enum PACKAGES

• When you are importing classes into your program, you may have noticed that all of the included parts of the API are organized into packages that group related types • When you import something, the package structure tells Java where to look for the classes being imported • By default, when you run the java command everything in the current directory is considered in the same package and is effectively imported automatically • You can create your own packages and use them to create a directory structure for your own files (either for organizational purposes or for distribution) PACKAGES

• To include a class in a particular package, you just use the package keyword at the top of the file: package package.name; • This tells the compiler that you wish this class to be part of the package. • The package is considered part of the fully qualified name. You can refer to the class by using just the class name (known as the simple name) if the package is imported, or by using the fully qualified name if it is not imported • For example, if there was file in the package above that had a class named SomeClass then the class could be used without importing by referring to it as package.name.SomeClass • General practice is to begin your package names with the Internet domain of your organization in reverse order: com.deitel.package edu.fsu.package COMPILING PACKAGES

• When you are creating packaged types, you typically place them in a directory structure based on the full package name, with each dot representing a new directory • This is how the java command will search for the bytecode files when your program is running • You can have javac automatically place the files in this directory structure by using the -d option when compiling • Note that you must also give the top-level domain you wish the directories to be placed in when compiling (you use . to represent the current directory) • For example, to compile all of the java files in a directory and place the class files in a class structure with the current directory as the root of the class structure: javac –d . *.java • To compile all of the java files in a directory and place the class files in a class structure with ~/user/home/packages/ as the root of the class structure javac –d ~/user/home/packages *.java • Example of some files that use packages MORE EXAMPLES

• Examples from Deitel book (chapter 8)