Objects and Classes

A class is a set of data and methods that define the attributes and behavior of an object. It is used to model objects in the real world. Notice that the terms method and object are mentioned in the definition. Methods are called to perform operations on classes and objects while an object is an instance of a class.

 

Defining a Class

A class is declared with an optional public modifier followed by the keyword class, the class name and the class body.

class MyClass

{

// data

// methods

}

** Variables and methods are defined within the body of the class.

 

Concept of Superclass and Subclass

A superclass is the "parent" of all classes where data fields and methods are inherited. A subclass, on the other hand, inherits the data fields and methods of its superclass.

class mySuperClass {

. . .

}

class myClass extends mySuperClass {

. . .

}

class mySubClass extends myClass {

. . . {

}

 

In the example, class mySuperClass is the superclass where class myClass inherits all its data fields and methods. Therefore, myClass is the subclass of mySuperClass. At the same time, class myClass is the superclass of the class mySubclass. [Concept of Superclass and Subclass, 3 of 10]

Defining a Constructor

Constructors are the "builders" for a class. The constructor is called first when the class is used to create an instance at runtime. Similarly, it performs all the initialization for the object.

The constructor is defined within the body of the class with the public modifier followed by the class name, a parameter list, and the constructor body.

class MyClass

{

Public MyClass() {

}

}

The new operator

The new operator creates an instance of a class. It allocates space for a new instance and calls the class constructor which initializes the variables of the object.

MyClass NewClass = new MyClass();

Declaring Fields for a Class

A field definition is composed of the data type and the variable name. For example:

 

class myClass

{

int myField;

}

 

You can change the rules in accessing the data field by using the public, private and protected keywords. A public data field can be accessed by any part of a program, inside or outside of the class in which it is defined. A protected data field can only be accessed from within the class or from within a derived class (subclass). A private data field cannot even be accessed by a derived class.

Declaring a Method

Methods are like functions except that they are defined in a class, and operate on the member variables of the class.

Methods are defined within a class body. A method declaration follows the format below:

[acctype] <rettype> <methodname> ([parlist]);

Where:

[acctype] may be public (called from outside a class), private (callable only from within the class) and protected (callable only from the class and its derived classes).

<rettype> may be a primitive type, class name, an array or void.

<methodname> is the name of the method.

([parlist]) is a parameter list.

 

Passing Arguments to Methods

In Pass by Value, changes made inside a method do not affect the original value of the passed object. On the other hand, changes made on the objects passed by reference affect the original object. [Passing Arguments to Methods, 8 of 10]

To illustrate pass by value, take a look at the example class PassByValue. The values printed as a result of the method PassNow depends on the parameter passed from the main method (or where it is called). [Example: Pass By Value, 9 of 10]

To illustrate pass by reference, take a look at the example class PassByReference. The initial contents of the array arr[] (1,3,4,5,1,1,7) is changed to (0,3,4,5,0,0,7) as a result of the operations performed inside the methods. [Example: Pass By Reference, 10 of 10]

 

Java Keywords

The Java reserved words are listed below. Some of the keywords have no current meaning and are reserved for future expansion.

 

Break      switch      instanceof      byte      public

continue      catch      interface      char      static

do      finally      new      double      cast

for      throw      null      float      future

return      throws      super      int      generic

while      try      this      long      goto

case      abstract      import      const      inner

default      class      package      final      native

else      extends      synchronized      private      operator

if      implements      boolean      protected      outer

rest      transient      var      volatile      short

void      

 

Literals

Literals are the representation of values.

\n new line \r carriage return

\t tab \" double quote

\’ single quote \\ backslash

Comments

There are two regular comment styles, and a special comment style used to generate class library documentation.

// This is a comment

/* This is a comment */

/** This is a special comment for documentation **/

Rules in naming variables

Variables (identifiers) are names for classes, methods, variables and blocks. As in all programming languages, Java variables adhere to some rules, namely:

There are 3 kinds of variables in Java:

1. Instance variables

class VariableDemo {

int num1, num2;

double sum;

public void add ( ) {

sum = num1 + num2;

}

public void paint (Graphics g) {

g.drawString("The sum is "+sum,35,100);

}

}

 

In the example, variables num1 and num2 of type integer and sum of type double are declared as instance variables. These variables, therefore, can be accessed anywhere in the program (inside or outside the method). [Instance Variables,5 of 8]

 

2. Class Variables

class VariableDemo {

static int[] = {1,2,3,4,5,6,7};

. . .

}

The array I which is an array of integers is declared as a variable with a static value of {1,2,3,4,5,6,7}. Array i, being a class variable, is therefore accessible to the class and all its instances. [Class Variables, 6 of 8]

 

3. Local Variables

class VariableDemo {

String str;

public void displayString {

boolean more;

if (more) . . .

. . .

}

The variable more which of type boolean is local to method displayString. Once displayString finishes its execution, the variable more does not exist and may not be ued anywhere in the program. [Local Variables, 7 of 8]

Constants

Constants refer to those whose value does not change. In Java, the keyword final is used to refer to a constant.

class VariableDemo {

double charge1, charge2;

public void computeTemp() {

final double rate = 3.5;

. . .

}

}

The constant rate, which is of type double, has a constant value of 3.5. This value is retained throughout the course of the program. [Constants, 8 of 8]

Comparison Operators

Comparison operators are used to create comparison expressions, which result in a value of true or false.

 

= = equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

!= not equal to

 

Logical Operators

The comparison operators enable you to compare to expressions. Logical operators supercharge comparison operators so that you can combine two or more comparison expressions into a more complex logical expression.

Equal to rue if…

&& AND all expressions are true

|| OR only one expression is true

^ Exclusive-OR one and only one of the expression is true

! NOT Switches the value of a logical expression

 

Arithmetic Operators

Arithmetic operators are used for numeric computations.

 

+ Addition

- Subtraction

* Multiplication

/ Division

% Remainder

 

Assignment Operators

 

= Assignment

+= Addition

-= Subtraction

*= Multiplication

/= Division

%= Remainder

&= AND

|= OR

^= Exclusive-OR

 

Operator Precedence

All operators have an order of operations, or operator precedence. When you evaluate a complex expression, you must be sure to evaluate any sub-expressions in the correct order. Below is a list of all operators and their order of precedence.

 

++ Pre / Post-Increment

-- Pre / Post-Decrement

! NOT

(type) Cast

*,/,%,+,- Arithmetic Operators

<<>> >>> Bit-wise Operators

< . <= >= Relational Operators

= = != Equality

&, ^,| Logical Operators

 

Parentheses are used to group expressions so that they are easier to understand and to change the order of operations.