Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York...

47
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    225
  • download

    0

Transcript of Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York...

Evan KorthNew York University

Computer Science IClasses and ObjectsProfessor: Evan KorthNew York University

Evan KorthNew York University

Road Map

• Introduction to object oriented programming.• Classes• Encapsulation• Members• Objects• Constructors• Reading:

– Liang 5: chapter 6: 6.1 – 6.4– Liang 6: chapter 7: 7.1 – 7.4– Liang 7: chapter 7: 7.1 – 7.4

Evan KorthNew York University

Object Oriented Programming

• Emphasis is placed on nouns or objects.

• Nouns (objects) have properties and behaviors.

• How do we build these objects?

• How do we represent their properties?

• How do we define their behaviors?

Evan KorthNew York University

Classes

• The main building blocks of Java programs.

• Defines objects of the same type. Like a blueprint.

Evan KorthNew York University

Classes (cont)

• Every .java file has one or more classes. Only one of the classes can be a public class.– That class must have the same name as the .java file.

• If the class has an method called main(), execution can begin in that class. (Therefore, you can test a class by adding a main method to it.)

• If there are other classes in the file, they cannot be public classes.

Evan KorthNew York University

Encapsulation

• Encapsulation refers to the process of combining elements to create a new entity.

• You encapsulate the properties (attributes) and behaviors (activities) of an entity into a class.

• Encapsulation also enables us to hide the implementation of a class to other classes (information hiding / abstraction).

Evan KorthNew York University

Designing Classes

• A class declaration includes members of the class.

• A member can be either a data member or a method member.

• A data member (AKA field) is used to define state (attributes or properties) of the entity.

• A method member is used to define the behaviors of the entity.

Evan KorthNew York University

Data members

• Data members can be a primitive type or a reference to another object*.– Primitive types are integer types, floating point

types, characters and booleans. (Note: an int is not the same as an object of type Integer)

• The scope of a data member is the entire class, no matter where within the class it is declared.

* More on object references in a moment

Evan KorthNew York University

Default values for data members

• 0 for all numeric type variables (including both floating point types and all integer types)

• \u0000 for char variables• null for reference variables*• false for boolean type variables

• Note: No default values for local variables (variables declared inside a method).

* More on object references in a moment

Evan KorthNew York University

Objects

• An object is an instance of a class. • If we think of a class as a blueprint, an

object is one model created from that blueprint.

• You can create any number of objects from one class.

• An object is distinctly identified by an object reference (except for anonymous objects).

Evan KorthNew York University

Declaring object references

• In order to reference an object, we need an object reference variable.

• To declare an object reference variable we use the syntax:ClassName objectReferenceName;

• The above statement creates a variable objectReferenceName which can reference a ClassName object. It does NOT create an object.

Evan KorthNew York University

Instantiating objects

• In order to create an object, we use the new keyword along with a constructor* for the class of the object we wish to create.

• To refer to the object, we “point” an object reference variable to the new object.objectReferenceName = new Constructor();

• The declaration and instantiation can be combined as follows:ClassName objectReferenceName = new ClassName();

– Note: the name of a constructor is the same as the name of the class

* More on constructors soon

Evan KorthNew York University

Accessing Members of a Class

• Within a class you can access a member of the class the same way you would any other variable or method.

• Outside the class, a class member is accessed by using the syntax:– Referencing variables:

objectReferenceName.varName – Calling methods (sending messages):

objectReferenceName.methodName(params)

Evan KorthNew York University

Constructors

• Constructors are special methods that instantiate objects.

• A constructor is invoked with the new operator.

• A constructor should initialize the class variables. If the variables are not initialized, default values are used.

• A constructor does not have a return type.• A constructor’s identifier (name) is the

same as the class it constructs.

Evan KorthNew York University

Constructors continued• Constructors can be overloaded but each one must

have its own signature.• A constructor with fewer arguments can call a

constructor with more arguments (we will see how to do this soon).

• If no constructor is defined, a default constructor is automatically supplied which accepts no parameters. Variables are initialized to their default values.

• If one constructor is explicitly defined, the automatic default constructor is no longer available. In such case, if you want a no parameter constructor, you must define it yourself.

Evan KorthNew York University

Road Map

• Dealing with multiple files

• modifiers

• Static variables

Reading– Liang 5: chapter 6: 6.6, 6.7, 6.10, 6.11– Liang 6: chapter 7.5 – 7.8, 7.11, 7.14– Liang 7: chapter 7.5 – 7.8

Evan KorthNew York University

review

• What is meant by the term encapsulation?

• What are the default values for data members?

• What does it mean to instantiate an object?

• What does this statement do?

Integer i;

Evan KorthNew York University

Review

• Given:

Integer i;

What does the following statement do?

i = new Integer(100);• Generally, what should a constructor do?

• What is a default constructor?

Evan KorthNew York University

Modifiers

• Java provides us with several keywords used to modify the accessibility of variables, methods and classes.– Visibility modifiers

• public• private• protected• (None)

– others• static• final • abstract

Evan KorthNew York University

Principle of least privilege

• You should pick the modifier that allows the least privilege for other classes while allowing your code to do what it needs to do.

• This helps reduce debugging time by localizing potential problem areas.

Evan KorthNew York University

Data member modifiers• No modifier (default) means the data is visible in the

package in which it is declared.• public means the data is visible to everything.• private means the data is visible only within the

class in which it is defined.– Trying to access private data from another class will result in

a compile time error.

• final means the variable cannot be changed.• There are two other modifiers applicable to variables:

– static : We will discuss in a moment– protected: We will discuss later in the semester.

Evan KorthNew York University

Accessor methods

• When a data member is declared to be private, we still need a way to refer to that data. A method used to change or retrieve a private data item is referred to as an accessor method.

• Two kinds of accessor methods are the get method and the set method.

Evan KorthNew York University

Get methods

• A method that is used to retrieve the value of a data object is referred to as a get method.

• Also known as a getter.• Get method header should look like this:public returnType getPropertyName ()

• It may just return a data field or it may calculate the value. Remember information hiding.

Evan KorthNew York University

Predicate methods

• A get method that returns a Boolean value should have a header like this:

public boolean isProperty ()

• It can simply return a Boolean data field or it can use a Boolean formula to calculate it’s data. Remember, information hiding!

Evan KorthNew York University

Set methods

• Methods used to set or change the value of a data method are referred to as set methods.

• Also known as setters and mutators.

• Header of set method will look like this:public void setProp (propType var)

Evan KorthNew York University

Data modifiers (cont)

• A data member can be either an instance variable or a static variable (also known as a class variable).

Evan KorthNew York University

Static variable (AKA class variable)• A static variable has only one value no matter how

many objects are instantiated from a class. The value is shared by all instances of the class.

• A static variable does not need an instance of the class in order to be accessed.

• You can access a static variable either with ClassName.varName (better style), or objectReference.varName notation.

• For static variables, every object of the class refers to the same memory location.

• Static variables can be accessed by static methods OR instance methods.

• The memory for a static variable is allocated when the class is loaded into memory.

Evan KorthNew York University

Instance variables• An instance variable has a unique value for each

object of that class. – This does not mean that two objects cannot have the

same value; it does mean that those values will be stored separately in memory.

• You can access an instance variable only with objectReference.varName notation.

• No memory is allocated until an object is instantiated.

• Can be accessed by instance methods only (not static methods -- we will talk about static methods in just a moment). (i.e. not by static methods)

Evan KorthNew York University

Scope of data members

• Whether a data member is a class variable or an instance variable, it’s scope is the entire class. It does not matter where in the class, the variable is declared.

• Remember, if they are not initialized, data members are assigned a default value.

Evan KorthNew York University

Local method variables

• Do not automatically get initialized.– Using them without initializing them is a

compilation error.

• Cannot have visibility modifiers.

• The scope of a local method variable starts where it is declared. It ends at the end of the block where it was declared.

Evan KorthNew York University

Method members

• Methods are used to define the behaviors of an object.

• They can be overloaded. – Having more than one method in a class with

the same name is referred to as method overloading.

– Each of the methods must have a different method signature. That is, they must have different argument lists.

Evan KorthNew York University

Method modifiers• No modifier means the method is visible in the package

in which it is declared.• public means the method is visible to everything.• private means the method is visible only within the

class in which it is defined.– Trying to call a private method from another class will result

in a compile time error.• static means it is a static method. Static methods can

use other modifiers as well.• There are three others (final, protected and abstract) which we will discuss later in the semester.

• There are still others which we will not discuss this semester.

Evan KorthNew York University

Static methods (AKA class methods)

• Can be called without an instance of the method.

• All the methods in the Math class are static methods which is why we can call them without a Math object. In fact, we cannot instantiate an object of the Math class.

• You can call a static method either with ClassName.method (args) (better style), or objectReference.method (args) notation.

Evan KorthNew York University

Instance methods

• Can only be called after an object is instantiated.

• You can call an instance method only with the objectReference.method (args) notation.

• An instance method acts on the specific instance for which it has been called.

Evan KorthNew York University

Road Map• Class modifiers• Garbage collection• Naming conflicts

– this

• Reference members

• Reading: – Liang 5: chapter 6: 6.9, 6.12

– Liang 6: chapter 7: 7.10, 7.12, 7.13

– Liang 7: chapter 7: 7.9, 7.10, 9.3, 9.4

Evan KorthNew York University

review• What does encapsulation mean?• What is a data member?• What is a method member?• What is the difference between an object and a

class?• What does the following line of code do?

– Integer i;

• What is i above?• What happens if you make a class without a

constructor?

Evan KorthNew York University

Review (cont)

• What do the following modifiers mean when applied to a data member?– final– static– public– private

• What if there is no modifier?

• What is the principle of least privilege?

Evan KorthNew York University

Review (cont)• What data type does a set method usually return?• What parameter does a get method usually take?• A class has 3 objects instantiated, it also has a

static variable called x and an instance variable called y. – How many x values are stored in memory?

– How many y values are stored in memory?

• What is the scope of an instance variable?• Can you call an instance method without an

instance of the class?

Evan KorthNew York University

Class modifiers

• No modifier (default) means the class is visible in the package in which it is declared.

• public means it is visible to everything.

• There are two others (final and abstract) which we will discuss later in the semester.

Evan KorthNew York University

Garbage collection• When an object is no longer referenced by any

reference variable, that object is referred to as garbage.• Java automatically tracks garbage objects and frees its

memory when the garbage collector runs.• We do not have direct control over when the garbage is

collected.• We can suggest to the compiler to collect garbage but it

is not guaranteed that it will run. • To suggest garbage collection we make the following

method call:– System.gc();

Evan KorthNew York University

Anonymous objects

• An object without a reference is called an anonymous object.

• It is created, used and immediately marked as garbage.

Evan KorthNew York University

Variable name conflicts

• It is possible to have a variable name in a method with the same name as a data member in a class.

• In such case, the local method variable “hides” the data member variable.

Evan KorthNew York University

Keyword this• The keyword this is used within a class to refer

to the specific instance of the class that is being used.

• A variable in a class’ method that has the same name as a field will “shadow” the field. You can access the field using the this keyword.

• You cannot use the this keyword in static methods. (why?)

Evan KorthNew York University

Another use for this

• this (args) in a constructor will invoke another constructor of that class.– If you call another constructor from a constructor, it

must be the first line in the calling constructor.

• This is useful when you overload your constructors. In general, a constructor with fewer parameters should call a constructor with more parameters.

Evan KorthNew York University

Composition

• The term composition refers to the practice of having an object as a data member within another object.

• What is actually stored is a reference to the member object. (therefore we can have self referential objects)

• The default value for a reference variable is null.

Evan KorthNew York University

Passing reference variables to methods

• All variables in Java are passed using call by value. However, since object variables are really references to objects, passing an object is simulated pass by reference.– Objects passed to a method and modified by that

method will have the changes reflected in the calling method.

– Primitive variables passed to a method and modified by that method will NOT have the changes reflected in the calling method.

Evan KorthNew York University