Docsity

Java Programming: Understanding Objects, Classes, and Variables, Lecture notes of Computer Science

Partial preview of the text

Download Java Programming: Understanding Objects, Classes, and Variables and more Lecture notes Computer Science in PDF only on Docsity!

COM 413

OBJECTS & CLASSES

Introduction

  • (^) Object - Objects have states and behaviors. Example: A dog

has states-color, name, breed as well as behaviors -wagging,

barking, eating. An object is an instance of a class.

  • (^) Class - A class can be defined as a template/blue print that

describes the behaviors/states that object of its type

support.

Variable Types

  • (^) Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
  • (^) Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  • (^) Class variables: Class variables are variables declared within a class, outside any method, with the static keyword.

Creating an Object

There are three steps when creating an object from a class:

  • (^) Declaration: A variable declaration with a variable name with an object type.
  • (^) Instantiation: The 'new' keyword is used to create the object.
  • (^) Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Accessing Instance Variables and

Methods:

To access an instance variable the fully qualified path should be as follows:

/* First create an object */

ObjectReference = new Constructor();

/* Now call a variable as follows */

ObjectReference.variableName;

/* Now you can call a class method as follows */

ObjectReference.MethodName();