CISC-124 20180115 20180116 20180118 We continued our introductory exploration of Java and object-oriented programming by looking at a program that uses two classes. We created a Java file Dog.java and another called AllMyDogs.java. Both of these files are already available on the website but I will include them here as well. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing. // 20180115 // RWD public class Dog { // The Dog class has no "main" method. The main method // will be found in the AllMyDogs.java file String name; // Note that this variable is not "static". This means // that each Dog object will have its own copy of the // "name" variable. If this variable is "static" then // all the dogs will have the same name. // constructor for Dog Dog (String n){ // When we create a Dog object, this constructor method is // automatically run. Here we are just using it to assign // the dog's name name = n; } // end constructor
public String getname() { // It is considered bad programming style for // anything outside the Dog class to use direct // access to the attributes of the Dog object. // If access is needed, we create a "getter" // method that will return the value of the // variable, and... return name; } // end getname() public void setname(string n) { //... a "setter" method that will assign // a value to the variable. name = n; } // end setname() } // end class Dog The purpose of Dog.java is simply to define the attributes (variables) that define a Dog, and the methods (functions) that a Dog can execute. Defining the class Dog and including it in a program does not actually create any Dog objects they are only created when we execute a new Dog instruction, which we will see in the AllMyDogs.java file. In this very simple example, the only attribute is name and the only methods are getname and setname. There is one special method included in the class definition the method called Dog is a constructor method. Whenever a Dog object is created, this method is run automatically. We typically use constructor methods to assign values to the attributes of the object being created. Java classes do not have to have constructor methods but they usually do.
Now let s look at the AllMyDogs.java file. // 20180115 // RWD // When we added input to the Collatz program we used a Scanner object. //We had to import the java.util.scanner class to do that // In this program we are going to use Dog objects but we don t have to //import the definition of the Dog object because it is in the same project public class AllMyDogs { // main is in this file because this is the part of the program that actually // does the work public static void main(string[] args) { Dog dog1 = new Dog("Hudson"); // Declare a Dog variable called // dog1, then create a new Dog // object with name = "Hudson", and // connect it to the dog1 variable Dog dog2 = new Dog("Dixie"); Dog dog3 = new Dog("Max"); System.out.println("Dog 1's name is " + dog1.getname()); System.out.println("Dog 2's name is " + dog2.getname()); System.out.println("Dog 3's name is " + dog3.getname()); dog2.setname("marmaduke"); System.out.println("Dog 2's name is " + dog2.getname()); Dog dog4 = dog1; // Declare a new Dog variable called dog4, and assign // it the value of dog1 // This does NOT create a new Dog object - it makes // dog4 an alternative name for the Dog object that // dog1 refers to dog4.setname("clifford"); // So when we change the name of dog4... System.out.println("Dog 1's name is " + dog1.getname()); } // end main } // end class AllMyDogs //... the change shows up when we look at dog1
It s important to understand what happens when we execute a command such as Dog dog1 = new Dog( Hudson ); The word Dog says that we are creating a new variable of type Dog. Then dog1 is the name of the new variable. At this point, there is no Dog attached to this variable. Then new Dog( Hudson ) tells Java to create a new Dog object. The constructor from the Dog class is executed, which assigns Hudson as the name of the just-created Dog. Finally, the = links the variable dog1 to the new Dog whose name is Hudson. What is happening behind the scenes is that the dog1 variable is set up in such a way that it can contain a memory address. When the new Dog object is created, Java allocates a chunk of memory to store all the attributes of the new Dog. The address of that chunk of memory is what gets stored in dog1. So when we say something like dog1.setname( Farley ); what happens is that the memory address stored in dog1 is used to locate the proper chunk of memory, then the setname() method is used to update the name attribute that is stored in that area of memory. When we execute Dog dog4 = dog1; the current value of dog1 is copied to dog4... and since the value of dog1 is a memory address, that is what gets copied. So now dog1 and dog4 both hold the memory address of the same Dog object... which is why calling dog4.setname() changes the result we get from dog1.getname() - dog1 and dog4 are both pointing to the same object. In this simple code sample, we didn t talk too much about public versus private. Normally the attributes of an object are declared private, so they cannot be freely accessed from outside the class. This is part of information hiding which we will talk about a lot in this course. A word about static : notice that the name attribute of the Dog object is not declared static. If it had been declared as static String name; then there would be one variable called name in the Dog class, shared by all the Dog objects. This would have the result that all the dogs would have the same name. You should try this out put the word static in front of the name declaration and see what happens.
Primitive Types Java provides eight types of variables that are not objects which means that they just have values, not attributes or methods. These are: Integer types: byte: this type of integer variable is only allocated 1 byte of memory it can only hold values from -127 to +128 short: allocated 2 bytes of memory int: long: allocated 4 bytes of memory allocated 8 bytes of memory Real Number types: float: allocated 4 bytes of memory Other types: double: allocated 8 bytes of memory boolean: can be true or false char: can hold a single character such as x or & - the character can also be specified in unicode We normally only use four of these: int, double, boolean and char. Note that each primitive type name starts with a lower-case letter this helps us remember that they are not object type names, which usually start with upper-case letters (such as java.util.scanner) Generally, we can assign a value of one numeric type to a variable of a different numeric type if the second type is more general than the first.
We can summarize this in a diagram byte short int long float double which means that a byte value can be assigned to a variable of any type, short values can be assigned to any type except byte, etc. So the following operations are completely legal: byte x = 3; float y = x; short z = 99; long w = z; double u = w; // ha ha, double u = w but this is not: float x = 3; byte y = x; // this looks like an integer, but it is stored // as 3.0 because we are assigning it to a float // variable // fails because byte is more restricted than // float Non-Primitive Types Java provides two standard non-primitive data types: Strings and arrays Strings: we have seen these before, so we already know a bit about them. Notice that String are objects (hence the capital S), but they are so common that Java lets us create them a bit more easily than other objects. When we created a Dog, we had to do something like Dog dog5 = new Dog( Rover ); but to create a String, all we have to do is String astring = A nut for a jar of tuna ; String anotherstring = Borrow, or rob? ; Notice that unlike java.util.scanner, we do not need to import the String class. It is automatically included every time we run a Java program.
Since String is a class, you can expect that it has some predefined methods in fact, the String class has a lot of methods. We will look at two of them here, and I encourage you to look up the class and experiment with some of the methods. One very useful String method is charat(x) which returns the character in position x in the string. char somechar; String yetanotherstring = Mr. Owl ate my metal worm ; somechar = yetanotherstring.charat(5); Now somechar has the value w. (The first position in a String is position 0, the second position is position 1, etc.) Another String method that gets used a lot is length() int howlong = yetanotherstring.length(); Now howlong has the value 25 Exercise: what is wrong with this? char x = astring.charat(astring.length());
String equality can be tested with == (as with primitive types) and also with the String method equals. String astring = Draw evil on no live ward ; String bstring = Draw evil on no live ward ; Now if (astring == bstring) {...} and if (astring.equals(bstring)) {...} do exactly the same thing. Exercise: all of the strings in these examples are palindromes. Use methods in the String class to write a method that will test a String to see if it is a palindrome.
Arrays An array is a structure that allows us to store a collection of values of the same type, each one identified by its position in the collection. Arrays are also objects in Java, but they have a very different syntax for declaring them. An array declaration consists of a type, and a pair of square brackets. For example int[] myarray; boolean[] boolarray; Dog[] lotsofdogs; declares that myarray will be used to refer to an array of integers, boolarray will be an array of booleans, and lotsofdogs will be an array of Dog objects. Creating an array can be done in two ways: 1. by using new and specifying the size of the array. For example (using the array variables defined above) myarray = new int[100]; int x = 7; boolarray = new boolean[x]; lotsofdogs = new Dog[5]; and of course these two steps can be combined, as in double[] somenums = new double[19]; 2. by specifying the set of values to be stored in the array. This is called literal definition or declaration. It used curly braces, like this: String[] week = { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
The length of an array can be found by using length but unlike Strings, for arrays length is an attribute, not a method. So will not work, but will work just fine. int x = week.length(); int x = week.length;