classes - pccspot.pcc.edu/.../java_material/notes/classes.pdfclasses objectives: 1. define a class...

23
Classes Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields 5. instantiate objects from a class 6. invoke instance and class methods 7. understand object oriented concepts 8. understand the difference between class and instance methods 9. use constructors Contents Object Oriented Basic Concepts Classes Object Creation Constructors Anatomy of a Class Accessors and Mutators Building a class Using a class Additional Reading Object Oriented Basic Concepts Objects and Classes Java is an object oriented language. This means Java programs are created from objects. An object is a programming entity that is created from a class. A class defines the data in an object and what the object can do.

Upload: others

Post on 27-Apr-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

Classes

Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields 5. instantiate objects from a class 6. invoke instance and class methods 7. understand object oriented concepts 8. understand the difference between class and instance methods 9. use constructors

Contents Object Oriented Basic ConceptsClassesObject CreationConstructorsAnatomy of a ClassAccessors and MutatorsBuilding a classUsing a classAdditional Reading Object Oriented Basic Concepts Objects and Classes Java is an object oriented language. This means Java programs are created from objects.

An object is a programming entity that is created from a class.

A class defines the data in an object and what the object can do.

Page 2: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

I like to use the analogy of a cookie cutter being the mold or class and an actual cookie as the object. One mold can create many cookies; one class can create many objects. Class object object object Creating an object (Instantiation)

The process of creating an object is called instantiation. It's a big word that simply means: creating an instance from a class. Java comes with many predefined classes. You can create objects from these predefined classes. For instance, there are classes that do file input and output for you. There is a Math class that contains trigonometry functions. There are 1000's of predefined classes. You can also define your own classes and then create objects from them. You can simulate anything using the Java language. You could simulate a game, say baseball or soccer; a structure such as a skyscraper; a vehicle such as a car or a plane; a checking account; something that is fantasy, like another world. In order to do this, you would have to understand what you are simulating, figure out which classes you need and define them. Inheritance

A class can inherit from another class. This is called inheritance. Using inheritance can simplify your Java projects. With inheritance, you define a parent class and then a child class that inherits from the parent. In this way, you don't have to redefine things in the child class; they are passed down from the parent. You don't always use inheritance; only when you need it. Often you will use inheritance to take advantage of Java's predefined classes. Object communication

Page 3: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

Objects can communicate with each other by sending and receiving messages. For instance, an object might need to know the score of the game; it can send a message to the game object asking for the score; the game object would send back the score. some object what is the score? --> game object <-- the score is home team 3, away team 2 Data and Methods Objects are composed of methods and data. Data is the information an object holds. For instance, a soccer player object would information about that player: the player's number, position, height, weight, skill level, injuries, etc. Objects can do specific things (called methods.) For instance, if you were simulating a game of soccer, you could have a game object that calculates the time left in the game. The data and methods of an object are defined in the class the object is created from. Encapsulation (Information Hiding)

Objects don't tell other objects to know how they work. This is called encapsulation (information hiding.) For instance, if an object asks the game object for the time left in the game, it gets the time but doesn't know how the game object calculated it. Here is an analogy that I like to use. You order a pizza. How the delivery person got to your house is not known to you; and you don't care, as long as you get your pizza. How the game object calculates the game time is not important to the object that asked for it; as long as it gets the game time. This allows objects to change how they do things, independent of other objects.

Classes Java is an object-oriented language. An object is a program unit. Objects are created from a class. Java has pre-defined classes that you can use. You can also create your own classes. Think of a class as a template or mold. Think of an object as something made from the mold.

Page 4: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

For example, the mold for an automobile bumper is used to create actual bumpers. The mold would be like a class; the actual bumper would be the object. Many objects can be created from a class; as many as you need. Typically, a Java application consists of more than one class. Pre-Defined Java classes There are hundreds of Java classes already defined for your use. For example, there is a Math class. It in you'll find methods and constants that relate to math functions, such as cosine, sine, PI, etc. The System class is part of Java; you've already seen its println method. More about these pre-defined classes later as you use them in the course. What is in a class A class can contain these (among other) programmatic units:

• class methods • instance methods • class variables • instance variables • constants

How to create your own class To define a class, use the class keyword and give the class a name. By convention, class names begin with an uppercase letter. In general, use public for the access modifier. public class Employee { //code would go here }

How to create objects from a class Objects must be created from within a method. Object creation is also called instantiation (because you're creating an instance of a class). Here is how to create an object from the Employee class. Notice the use of the new keyword. This creates an object.

Page 5: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

public class Test { public static void main (String[] args) { Employee emp = new Employee(); } }

A class can contain two kinds of methods: • instance • class (also called static methods)

How to define instance methods An instance method is one that is used with an object. Here is a method that displays a string to the console. It accepts a string argument. There is no return value. public class Employee { public void display(String word) { System.out.println(word); } } How to use an instance method Here is how to use the instance method shown above. Create an object of the class and then specify the objectname.methodname. public class Test { public static void main (String[] args) { Employee emp = new Employee(); emp.display("Hello");

Page 6: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

} } How to define class methods

A class method is one that can be used without an object. It is defined with the keyword static. Here is the same display method, written as a static method. The only difference is the static keyword. public class Employee { public static void display(String word) { System.out.println(word); } } How to use a class method Use a static method by specifying the classname.methodname. public class Test { public static void main (String[] args) { Employee emp = new Employee(); Employee.display("Hello"); } } How to define instance variables Instance variables are one per object. That is, every object created from a class has its own copy of an instance variable.

Page 7: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

Define an instance variable like you would any variable, but define it in the class, not in a method. Use the private keyword. Here is a class with three instance variables. Notice they are not located in a method, but rather in the class. public class Employee { private String lastName; private String firstName; private int age; public static void display(String word) { System.out.println(word); } } How to define class variables A class variable has only one copy per class. All objects of the class share it. A class variable is like a constant. It is used to hold a value that is shared by all objects of a class. Use the static keyword to define a class variable. public class Employee { private static String CompanyName = "Nordstrom"; public static void display(String word) { System.out.println(word); } } How to define constants

Page 8: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

This was covered in a previous section of the course material.

Object Creation

When you create an object, you actually create two things: • an object reference • the object

The object reference is a small piece of memory (RAM) that contains the address of the object. The object is a piece of memory that holds the data and methods as defined in the class for the object. Suppose you have a class defined named Car. It contains one method and one data field. public class Car { private int age; public int getAge() { return age; } }

In another class named Test, in its main method, you create a new Car object. public class Test { public static void main(String[] args) { Car c; c = new Car(); }

Page 9: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

} The statement: Car c; creates the object reference in memory (RAM). This will point to the location of the object. Right now it doesn't point anywhere. The statement: c = new Car(); allocates memory for the actual object. The new keyword causes the memory to be allocated. c now contains the memory address of the car object. In memory (RAM), there are now the object reference and the object. They are two distinct areas in RAM. RAM c object reference contains the RAM address of the car object

car object

contains the data for the object

The important point to remember is that there are two areas of RAM allocated:

• one for the object reference • one for the object itself

Page 10: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

By the way, you can create the object reference and the object in one statement. Car c = new Car();

Constructors A Java class can have zero or more constructor methods. A constructor method is called automatically when an object of the class is created. How to define a constructor The name of a constructor method is always the same name as the class. Here is the Employee class with a constructor defined. public class Employee { public Employee() { //code would go here } }

You do not invoke a constructor directly; it is automatically invoked when you create an object. In the following example, the Employee constructor would be invoked for you: public class Test { public static void main (String[] args) { Employee emp = new Employee(); } }

Page 11: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

Anatomy of a Class How a Java class is defined

• An access modifier is specified, usually public. • A Java class is defined using the class keyword. • The class must have a name. The name must conform to Java identifier naming

rules. • Starting and ending curly braces { } enclose the class.

public class Employee { }

Class members A class can contain these (among other) programmatic members:

• instance methods • class methods • instance variables • class variables

How to define instance methods An instance method is one that must be used with an object. (More detail on defining and using methods is given in other sections of the course.) public class Employee { public void display(String word) { System.out.println(word); }

Page 12: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

} How to define class methods A class method is one that is used without an object. It is defined with the keyword static, which tells Java it is a class method. public class Employee { public static void show(String word) { System.out.println(word); } } How to define instance variables An instance variable is used to hold data for an object. That is, every object created from a class has its own copy of an instance variable. In general, use the private access modifier for instance variables. public class Employee { private String lastName; } How to define class variables A class variable has only one copy per class. All objects of the class share it. It is used to hold a value that is shared by all objects of a class. Use the static keyword to define a class variable. The static keyword tells Java it is a class variable.

Page 13: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

public class Employee { private static String CompanyName = "Nordstrom"; } Here is a class showing all the members described above. public class Employee { private String lastName; private static String CompanyName = "Nordstrom"; public void display(String word) { System.out.println(word); } public static void show(String word) { System.out.println(word); } } Note: A class can have as many members as is necessary. There are other things that can be contained in a class, such as constants.

Accessor and Mutator methods

Page 14: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

Instance variables are defined as private and cannot be accessed or changed directly from another class. Here is the Employee class with three instance variables and a Test class that tries to use the variables. Since they are private, they cannot be accessed directly. public class Employee { private String lastName; private String firstName; private int age; public static void display(String word) { System.out.println(word); } } public class Test { public static void display(String word) { Employee emp = new Employee(); emp.lastName = "Jones"; //this will fail } } How to make instance variables accessible To correct this shortcoming, define an accessor method and a mutator method for each instance variable. The accessor method is used to get the value of the variable. The accessor method should begin with get. The mutator method is used to store a value in the variable.

Page 15: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

The mutator method should begin with set. Here is the Employee class with accessor and mutator methods defined for the lastName variable. public class Employee { private String lastName; private String firstName; private int age; //mutator method for lastName variable public void setLastName(String s) { lastName = s; } //accessor method for lastName variable public String getLastName() { return lastName; } } Once there is an accessor/mutator pair of methods, the variable can be changed or retrieved. public class Test { public static void display(String word) { Employee emp = new Employee(); emp.setLastName("Jones"); System.out.println(emp.getLastName()); } }

Page 16: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

Building A Class Example Here is an example of how to build a class. This example builds a class to represent a movie. Step 1 Pick a name for the class The name of the class is Movie. Step 2 Decide what data you need to store The data I've chosen to use: moviename year format (VHS, DVD) director studio Step 3 Declare an instance variable for each piece of data private String movieName; private int year; private String format; private String director; private String studio; Step 4 Write constructors Here I choose to write three constructors. You can write as many as you want. public Movie() { movieName = ""; year = 0; format = ""; director = "";

Page 17: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

studio = ""; } public Movie(String name, int yearReleased) { movieName = name; year = yearReleased; format = ""; director = ""; studio = ""; } public Movie(String n, int y, String f, String d, String s) { movieName = n; year = y; format = f; director = d; studio = s; } Step 5 Write accessor methods public String getName() { return movieName; } public String getDirector() { return director; } public String getFormat() { return format; } public String getStudio() { return studio; } public int getYear() { return year; } Step 6 Write mutator methods

Page 18: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

public void setName(String n) { movieName = n; } public void setYear(int y) { year = y; } public void setDirector(String n) { director = n; } public void setStudio(String n) { studio = n; } public void setFormat(String n) { format = n; } Here is the entire class. public class Movie { //instance variables private String movieName; private int year; private String format; private String director; private String studio; //Constructors public Movie() { movieName = ""; year = 0; format = ""; director = ""; studio = ""; } public Movie(String name, int yearReleased) { movieName = name; year = yearReleased; format = "";

Page 19: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

director = ""; studio = ""; } public Movie(String n, int y, String f, String d, String s) { movieName = n; year = y; format = f; director = d; studio = s; } //Accessor methods public String getName() { return movieName; } public String getDirector() { return director; } public String getFormat() { return format; } public String getStudio() { return studio; } public int getYear() { return year; } //Mutator methods public void setName(String n) { movieName = n; } public void setYear(int y) { year = y; } public void setDirector(String n) {

Page 20: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

director = n; } public void setStudio(String n) { studio = n; } public void setFormat(String n) { format = n; } }

Using a Class This examples shows how to use a class. The Movie class code is used. On the left is a test program that uses the class. On the right is the Movie class. Some sections of code are colored. For example, Movie film1 = new Movie("Bambi", 1965); This indicates that the statement new Movie("Bambi", 1965); causes the constructor marked in yellow in the Movie class to be invoked. public class Test { public static void main (String[] args) { //Create a Movie object Movie film1 = new Movie("Bambi", 1965); //Get a value System.out.println(film1.getName());

public class Movie { //instance variables private String movieName; private int year; private String format; private String director; private String studio; //Constructors public Movie()

Page 21: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

//Create another Movie object Movie myFilm = new Movie(); //Set some values myFilm.setName("Dumbo"); myFilm.setYear(1960); }

{ movieName = ""; year = 0; format = ""; director = ""; studio = ""; } public Movie(String name, int yearReleased) { movieName = name; year = yearReleased; format = ""; director = ""; studio = ""; } public Movie(String n, int y, String f, String d, String s) { movieName = n; year = y; format = f; director = d; studio = s; } //Accessor methods public String getName() { return movieName; } public String getDirector() { return director; } public String getFormat() { return format; } public String getStudio() { return studio; } public int getYear() { return year; } //Mutator methods

Page 22: Classes - PCCspot.pcc.edu/.../Java_Material/notes/Classes.pdfClasses Objectives: 1. define a class 2. define class methods 3. define instance methods 4. define private and static fields

public void setName(String n) { movieName = n; } public void setYear(int y) { year = y; } public void setDirector(String n) { director = n; } public void setStudio(String n) { studio = n; } public void setFormat(String n) { format = n; } }

Additional reading Here is material from the java.sun.com website that applies to this unit. Object-Oriented Programming Concepts What Is an Object? What Is a Message? What Is a Class? What Is Inheritance? What Is an Interface? How Do These Concepts Translate into Code? Object Basics and Simple Data Objects The Life Cycle of an Object Creating Objects Using Objects