0% found this document useful (0 votes)
19 views26 pages

Java Summary

Java notes OOP

Uploaded by

Samuel Themba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
19 views26 pages

Java Summary

Java notes OOP

Uploaded by

Samuel Themba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 26

Variable Declarations

In a Java program, you must declare a variable before it can be used. A variable declaration
has the following form:

**SYNTAX

Type Variable_1, Variable_2;

**Data type: A data type specifies a set of values and their operations(e.g. int, double, long,
etc.)

#All primitive type names in Java begin with a lowercase letter

#Names of classes—begin with an uppercase letter

% The technical term for a name in a programming language, such as the name of a variable, is
an identifier ,should not use the $ symbol in your identifiers-It is intended to identify code
generated by a machine

% The name of something in a Java program, such as a variable, class, or method, is called an
identifier

**Combining a Variable Declaration and an Assignment

You can combine the declaration of a variable with an assignment statement that gives the
variable a value.

**SYNTAX

Type Variable_1 = Expression_1, Variable_2 = Expression_2;

Fix the variable’s value so that it cannot be changed:


SYNTAX:
public static final Type variable = Constant; // must be outside of main method
// Must be before public static void main(String[] args){}

e.g.
public static final double PI = 3.14159;

% The word public says that there are no restrictions on where you can use the name PI.
% The word final means that the value 3.14159 is the final value assigned to PI or, to phrase it
another way, that the program is not allowed to change the value of PI.

**Assignment Compatibilities

% A value can be assigned to a variable whose type allows more precision:

e.g.
byte -> short -> int -> long -> float -> double -> char

% It is also legal to assign a value of type char to a variable of type int or to any of the numeric
types that follow int in our list of types

**TYPE CASTING

% Involves putting the type that you want to change into in front of the variable you wanna
change.

double distance = 9.0;


int points = distance: // Illegal

int points = (int)distance; // Legal although truncation and lost of data may
occur as result of you not following a certain hierarchy.

% The expression (int)distance is called a typecast

% Neither distance nor the value stored in distance is changed in any way. But the value stored
in points is the “int version” of the value stored in distance. If the value of distance is 25.36, the
value of (int)distance is 25. So points contains 25, but the value of distance is still
25.36(**truncation not rounded)

**Division and Integer Division

% This operand can be both used for division as well as integer division depending on whether
we are dividing an int and a double, or an int and int.

9.0/2 = 4.5 // normal division

9/2 = 4 // integer division


// how many times a number goes into the other.

**INCREMENT AND DECREMENT


% Increment operator:

e.g. count++; // Increases count by 1


OR

e.g. count = count +1;

e.g. count += 1;

% decrement operator:

e.g. count--; // decreases count by 1


OR

e.g. count = count - 1;

**MORE ON INCREMENT DECREMENT

% Given n*(++m), and n = 3 and m = 4;

output = 15 // since the increment operator is before the value m, m is incremented


first then multiplied by n

% n*(m++) ,

output = 12 // since the increment operator is after the value m , the expression n*m
is calculated first then m is incremented after

% Note that the string " " is not empty: It consists of one blank character.
%All objects of a class have the same methods
%Spaces, special symbols, and repeated characters are all counted when computing the length
of a string. For example, suppose we declare String variables as follows: String command = "Sit
Fido!"; String answer = "bow-wow";

**Methods

% It is important to note that each escape sequence represents one character, even though it is
written as two symbols. So the string ""Hi"" contains four characters—a quote, H, i, and another
quote—not six characters. This point is significant when you are dealing with index positions

**Java Comments

There are three ways to add comments in Java:

• Everything after the two symbols / / to the end of the line is a comment and is ignored by the
compiler.
• Anything written between the symbol pairs / and / is a comment and is ignored by the
compiler. • Anything written between the symbol pairs /* and / is a comment that is processed
by the documentation program javadoc but is ignored by the compiler.

public class CircleCalculation2


{
public static final double PI = 3.14159;
public static void main(String[] args)

{
double radius; //in inches
double area; //in square inches
Scanner keyboard = new Scanner(System.in);

System.out.println("Enter the radius of a circle in inches:");

radius = keyboard.nextDouble();
area = PI * radius * radius;

System.out.println("A circle of radius " + radius + " inches");


System.out.println("has an area of " + area + " square inches.");
}
}

**CHAPTER 3 (Flow of Control)


Branching

if (condition/Boolean expression)
// execute statement1
else
// execute statement2

% We can also use the if statement without the else statement (this in turn continues executing
the program).

if (Boolean expression)
execute statement1
execute statement2

**The (and) operator

in java we use **&& operator for joining to expressions instead of using an inequality sign.
e.g.
if ((pressure > min) && (pressure < max))
System.out.println("Pressure i OK.");
else
System.out.println("Warning: Pressure is out of range.");

min < pressure < max // Incorrect

**The (or) operator

in java we use the or operator (| |) to compare to expressions.

e.g.
if ((salary > expenses) || (savings > expenses))
System.out.println("Solvent");
else
System.out.println("Bankrupt");

In Java we use equals method to equate two strings not == two equals signs

e.g.
if ("Hello".equalsIgnoreCase("hello"))
System.out.println("Equal");

OR

s1.equals(s2) // returns true if the two strings have equal strings


s2.equals(s1)

**Testing Strings for Equality

e.g.
import java.util.Scanner;
public class StringEqualityDemo
{ public static void main(String[] args)
{ String s1, s2;
System.out.println("Enter two lines of text:");
Scanner keyboard = new Scanner(System.in);
s1 = keyboard.nextLine();
s2 = keyboard.nextLine();
if (s1.equals(s2))
System.out.println("The two lines are equal.");
else System.out.println("The two lines are not equal.");

if (s2.equals(s1))
System.out.println("The two lines are equal.");
else System.out.println("The two lines are not equal.");

if (s1.equalsIgnoreCase(s2))
System.out.println( "But the lines are equal, ignoring case.");
else System.out.println( "Lines are not equal, even ignoring case.");
}
}

% When applied to two strings (or any two objects), the operator == tests whether they are
stored in the same memory location

**The ternary operator

e.g.
if (hoursWork <= 40)
pay = hoursWorked * payRate;
else
pay = 40 * payRate + 1.5 * payRate * (hoursWorked − 40);

Can be written as:


pay = (hoursWork <= 40)? (hoursWorked*payRate): (40*payRate+ 1.5 *
payRate* (hoursWorked-40));

% Most operating systems use 0 to indicate a normal termination of the program and 1 to
indicate an abnormal termination of the program (just the opposite of what most people would
guess). Thus, if your System.exit statement ends the program normally, the argument should be
0. In this case, normal means that the program did not violate any system or other important
constraints. It does not mean that the program did what you wanted it to do. So you would
almost always use 0 as the argument

% Highest
Precedence First: the unary operators +, , ++, , and!
Second: the binary arithmetic operators *, /, %
Third: the binary arithmetic operators +,
Fourth: the boolean operators <, >, <=, >=
Fifth: the boolean operators ==, !=
Sixth: the boolean operator &
Seventh: the boolean operator |
Eighth: the boolean operator &&
Ninth: the boolean operator ||
Lowest Precedence

**Short-Circuit Evaluation

For a boolean expression of the form Expr_A || Expr_B, if Expr_A is true, Java concludes that
the entire expression is true without evaluating Expr_B. Likewise, for an expression of the form
Expr_A && Expr_B, if Expr_A is false, Java concludes that the entire expression is false without
evaluating Expr_B.

**The switch statement

e.g.
switch (Controlling_Expression)
{
case Case_Label:
Statement;
break;

case Case_Label:
Statement;
break;

default:
Statement;
break;}

1.The Controlling_Expression must be of an integer type such as int,


short, or byte, or of type char or string.

2.Each Case_Label is a constant of the same type as the


Controlling_Expression. Each case must have a different Case_Label. A
break may be omitted. Without a break, execution just continues to the
next case.

3.Any number of cases is allowed.


4.A default case is optional. Without one, no action occurs in the
event of a mismatch.

EXAMPLE

int seatLocationCode;
switch (seatLocationCode)
{
case 1:
System.out.println("Orchestra.");
price = 40.00;
break;
case 2:
System.out.println("Mezzanine.");
price = 30.00;
break;
case 3:
System.out.println("Balcony.");
price = 15.00;
break;
default:
System.out.println("Unknown ticket code.");
break;
}

**Enumerations

% An enumeration lists the values that a variable can have.

e.g.
enum MovieRating {EXCELLENT, AVERAGE, BAD};

An enumeration acts as a class type, so we can use it to declare a variable


rating, as follows:

MovieRating rating = MovieRating.AVERAGE;

% to assign A to rating. Note that we must preface the value A with the name of the
enumeration and a dot. Assigning a value other than E, A, or B to rating will cause a syntax
error

**Dialog Boxes for Yes-or-No Questions

The class JOptionPane in the package javax.swing defines the method show-ConfirmDialog.
You can use this method to create a dialog box to ask a yes-or-no question and get the user's
response.

**SYNTAX

Integer_Response = JOptionPane.showConfirmDialog(null, Question_String, Title_String,


Option);

The displayed dialog box is titled Title_String and contains the text Question_String and buttons
as indicated by Option. When Option is JOptionPane.YES_NO_OPTION,two buttons labeled
Yes and No are displayed. The method returns the int constant YES_OPTION if the user clicks
the Yes button, or NO_OPTION if the user clicks the No button.

**EXAMPLE

int answer = JOptionPane.showConfirmDialog(null, "Done?", "Click a Button:",


JOptionPane.YES_NO_OPTION);

**JAVA_LOOP

% While-loop == repeated until the body expression evaluates to false.


% Sometimes not executed zero times.

while (Boolean_Expression)
Body

The Body may be either a simple statement or, more likely, a compound
statement consisting of a list of statements enclosed in braces {}.

e.g.
//Get next positive integer entered as input data
int next = 0;
while (next <= 0)
next = keyboard.nextInt(); //keyboard is a Scanner object
//Sum positive integers read until one is not positive
int total = 0;
int next = keyboard.nextInt();
while (next > 0)
{ total = total + next;
next = keyboard.nextInt();}

% do-while statement
% Is executed at least once
%The (do-while) loop unlike the (while loop) executes the body of statements first then follows
up by the control Boolean expression( And do not forget a semi-colon after the last Boolean
expression.
)

e.g.
do {
first_Staement
Last_Statement
}
while (expression)

After the first body is executed the do-while loop then acts like a normal
while loop.

e.g.2
import java.util.Scanner;
public class DoWhileDemo
{
public static void main(String[] args)
{ int count, number;
System.out.println("Enter a number”);
Scanner keyboard = new Scanner(System.in);
number = keyboard.nextInt();
count = 1;
do
{
System.out.print(count + ", ");
count++; }
while (count <= number);
System.out.println();
System.out.println("Buckle my shoe.”);
}
}
% The for-statement/loop

e.g
for (count = 1; count <= 3; count++)
Body
is equivalent to
count = 1;
while (count <= 3) {
Body count++;
}

for (Initializing_Action; Boolean_Expression; Update_Action)


Body

e.g.2.
// Counting down
public class ForDemo
{
public static void main(String[] args)
{
int countDown;
for (countDown = 3; countDown >= 0; countDown−−) {
System.out.println(countDown);
System.out.println("and counting.”); }
System.out.println("Blastoff!”);
}
}

% Declaring a variable within a (for) statement

e.g.
for (int count = 0; count <= 10; count++)
// In this case count is local to the for loop and cannot be used
anywhere else.
The scope of the varaible count is thus the for loop.
A scope is where a variable can be used.

%The for statement in a (for) loop


e.g.
// it acan be used to separate multple initialization steps
for (n = 1, product = 1; n <= 10; product *= n, n++)
//This forms a for loop without a loop body although it
is still useful.

Classes

The **for-each statement

% Can be used when we have a collection of data in (Enumeration form)

e.g.
// For a game of cards
enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES}
for (Suit nextSuit : Suit.values())
System.out.println(nextSuit+" ");
System.out.println();

//The expression Suit.values() represents all the values in


theenumeration. The variable nextSuit takes on each of these values
one at a time as the iteration progresses.
Thus, the output from this loop is:
CLUBS DIAMONDS HEARTS SPADES

**Break statement and Continue statement in loops

% The break statement ends the innermost part of the switch statement or the loop.

% A continue statement ends the current iteration and begins another one.

% You should try and avoid these within loops.

**Loop bugs

Two common loops


// Infinite loops
// Off-by-one-errors (using < instead of <=)
always use something involving less-than or greater-than, such as <=. Using == or != to
compare floating-point numbers can produce an off-by-one error, an unintended infinite loop.

**Assertion in java
% Assertion checks in java involve asserting that a certain line of code is true or not.

An assertion check has the following format:


e.g.
assert Boolean_Expression

// if the assertion evaluates to false the program ends after displaying a


message that assertion has failed

you can turn assertion checking on and off by using the command line:
java −enableassertions YourProgram

**Junit and JGrasp

configure the JUnit plug in for use with the version of JUnit that you have installed
open a source file in jGRASP and create a corresponding test file;
create test cases (test methods) in the test file for each of the methods in the source file
run the test file for a corresponding source file;
run all test files for a project
view the results of running the test files in the JUnit window

**Fixing errors encountered during testing

1. ) set a breakpoint in the test file at the statement where the source method is called
2. ) run the test file in debug mode. After the program stops at the breakpoint, step-in to the
source method
3. ) single-step, looking for the statement that is responsible for the failure

%Unit Testing: Testing one unit or component at a time (e.g., testing a class and its methods).

%Failure: An undesired (incorrect) result produced by the software.

%Fault (or Defect): The underlying cause of the failure (a “bug” or “error” in your code).

%The purpose of testing is to identify failures so that the underlying faults (or defects)can be
removed.

%Debugging is the process of removing a fault. (Note that debugging occurs after a failure has
revealed the existence of a fault.)

**When comparing integer values or objects:


Assert.assertEquals(expected, actual);
Assert.assertEquals(error msg, expected, actual);

**When comparing float or double values:

Assert.assertEquals(expected, actual, delta);


Assert.assertEquals(error msg, expected, actual, delta);

%delta is the number of decimal points to round off to.

**Arrays

Creating and accessing arrays

An array is a collection of variables of the same type.


We can declare an array consisting of seven variables as follows;

double[] temperature = new double[7];

variables like temperature[0] or temperature[1] are called index variables.


All seven variables declared can be used just like any other variable of type double.

e.g. temperature[3] = 33;


temperature[6] = temperature[3]+ 5;
System.out.println(temperature[6]);

Since index is an expression we can write a loop to read values into the array
temperature, as follows:

System.out.println("Enter 7 temperatures:")
for (int index; index<7; index++){
temperature[index] = keyboard.nextDouble();
}

And we can output the seven temperatures as follows;

System.out.println("The seven temperatures are:")


for (int index=0, index<7; index++){
System.out.println(temperature[index])
}

Remember an array is an object meaning that you create an array the same way you
would create an object of a class type using the new operator.

Base_type[] Array_Name = new Base_Type[length]; // declares and


allocates memory for the array Array_Name of length.

e.g. int[] pressure = new int[100]; // creates 100 variables of type int (pressure[0],
pressure[1], pressure[2],..., pressure[n])
Alternative way to declare variables is:

char alphabet[] = new char[100]; // after the variable name instead of


the base type.

It is advisable to use an integer constant instead of an integer literal

public static final int NUMBER_OF_READINGS = 100;


int[] pressure = new int[NUMBER_OF_READINGS];

You can also read in the length of an array instead of declaring it yourself
Always use singular form for an array name, instead of entries->use entry
instead of cars-> use car
You cannot change the size/length of an array once declared.
Always use a for loop or for-each statement to step through an array.

for (int value : temperature) {


if (value < average)
System.out.println(value + " below average.");
else if (value > average) System.out.println(value + " above
average.");
else
//value == average
System.out.println(value + " the average.");
}

Remember the last index in an array is lengthOfArray-1


**Initializing Arrays

double[] reading = {3.3, 15.8, 9.7};

This is initialization declaration statement is equal to

double[] reading = new double[3];


reading[0] = 3.3;
reading[1] = 15.8;
reading[2] = 9.7;

**Arrays In Classes and Methods

Arrays can be used as instance variables in classes.


Methods can have an indexed variable or an entire array as an argument and can return
an array.
When you create an array of objects java doeas not create instances of any of the objects.

e.g. SalesAssociate[] team = new SalesAssociate[10];

The array is created and holds ten references. In other words, there are ten addresses to
memory locations that can store SalesAssociate objects .Java uses special value null to
mark empty references.
To access an array we need to reference an object.

e.g. team[0] = new SalesAssociate("Jane Doe", 5000);


team[1] = new SalesAssociate("John Doe", 5000);

An indexed variable such as a[i] can be used anywhere you can use any other
variable of the base type of the array.
Thus it can be an argument to a method.

**Indexed Variables as Arguments

e.g.
double[] a = new double[3];
// Indexed variables such as a[3] and a[i] can thus be used as arguments
A parameter can also represent an entire array.
Array parameters do not specify array length.

e.g.
public static void ShowArray(char[] a)

**Arguments for the Method main


You can pass an array of strings to main as an argument

e.g.
public static void main(String[] args){}
// args[0],args[1],..,args[i]

**Array Assignment and Equality


Since arrays are objects they behave and misbehave like other objects.
Arrays are stored in such a way that they share the same memory address.
**Assignment operator

int[] a = new int[3];


int[] b = new int[3];
for (int i = 0; i <a.length; i++)
a[i] = i;
b = a;
System.out.println("a[2] = " + a[2] + ", b[2] = " + b[2]); a[2] =
2001;
System.out.println("a[2] = " + a[2] + ", b[2] = " + b[2]);

This will produce the following output:


a[2] = 2, b[2] = 2
a[2] = 2001, b[2] = 2001
// The assignment b = a int he preceding code gives the array variable
b the same memory address as the arrya variable a.

**The Equality operator


Tests whether the two arrays a and b are stored in the same place in the computers
memory

% If you want to test whether two arrays contain the same elements, must test whether each
element in one array equals the corresponding element in the other array.
%You can use the assignment operator = to give an array more than one name. You cannot use
it to copy the contents of one array to another, different array. Likewise, the equality operator ==
tests whether two array names reference the same memory address. It does not test whether
two different arrays contain the same values.

**Returning an array
Syntax

public static Base_Type[] Method_Name(Parameter_List) {


Base_Type[] temp = new Base_Type[Array_Size];
Statements_To_Fill_Array
return temp;
}

e.g.
public static Base_Type[] Method_Name(Parameter_List) {
Base_Type[] temp = new Base_Type[Array_Size];
Statements_To_Fill_Array return temp;
}

%A private instance variable that has an array type can be modified outside of its class, if a
public method in the class returns the array. This is the same problem we discussed in the
previous chapter, and it has analogous solutions.

**Programming with Arrays and Classes

**Inheritance Polymorphism, and interfaces

Inheritance lets you define specialized classes from a general one.

public class Person {

private String name;


public Person() {
name = "No name yet";
}
public Person(String initialName) {
name = initialName;
}
public void setName(String newName) {
name = newName;
}
public String getName(){
return name;
}
public void writeOutput(){
System.out.println("Name: " + name);
}
public boolean hasSameName(Person otherPerson){
return this.name.equalsIgnoreCase(otherPerson.name);
}
}

Person
- Student
- Undergraduate
- Graduate
- Masters
- Doctoral
- Nondegree
- Employee
- Faculty
- Staff

A derived class extends a base class/ super class/ancestor/parent and inherits the base
class's public members.
In the example student extends Person:

public class Student extends Person {


private int studentNumber;
public Student() {
super(); // super is explained in a later section. Do not worry
about it until you reach the discussion of it in the text.
studentNumber = 0;//Indicating no number yet
}
public Student(String initialName, int initialStudentNumber) {
super(initialName);
studentNumber = initialNumber;
}
public void reset(String newName, int newStudentNumber) {
setName(newName);
studentNumber = newStudentNumber;
} public int getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(int newStudentNumber) {
studentNumber = newStudentNumber;
}
public void writeOutput() {
System.out.println("Name: " + getName());
System.out.println("Student Number: " + studentNumber);
}
public boolean equals(Student otherStudent) {
return this.hasSameName(otherStudent) && (this.studentNumber ==
otherStudent.studentNumber);
}
}

We cannot directly access the instance variable name since it is private to Person class ,
but we can use public methods defined in Person class to change the name of the student
object.
A Demonstration of Inheritance Using Student

public class InheritanceDemo {


public static void main(String[] args) {
Student s = new Student();
s.setName("Warren Peace")
s.setStudentNumber(1234);
s.writeOutput();
}
}

A method Overrides another method if both have the same name, return type and
parameter list
In a derived class, if you have a method with the same name, number of parameters and
types, and the same return type as a method already in the base class, this new definition
replaces the old definition of the method when objects of the derived class receive a call to
the method.
A method overloads another if they both have the same name and return type but different
parameter list
A final method cannot be overridden.
An entire class can be declared final, thus it cannot be used as a base class to derive any
other class.
A derived class can call public methods of the base class of which in turn calls a private
method when both methods are in the same class.

% An object of the derived class will inherit public and private instance variables of the base
class, but it cannot directly access the private instance variable.

**Programming with Inheritance

**Constructors in derived classes

A derived class does not inherit constructors from the base class
Constructors in the derived class invoke constructors in the base class
Any call to super/base class must be first within a constructor
without super/ omitting super a constructor invokes the default constructor in the base
class

public Student() {
super();
studentNumber = 0;//Indicating no number yet
}

is completely equivalent to the following definition:

public Student() {
studentNumber = 0;//Indicating no number yet
}

You can use this and super to invoke a constructor


this invokes the constructor of the same class, and super invokes a constructor of the
base class.
A revised call to the default constructor in Person is as follows:

public Person() {
this("No name yet");
}
In this way, the default constructor calls the constructor public

Person(String initialName) {
name = initialName;
}

Using super as an object calls a base-class method/**Overridden method


e.g.

public void writeOutput() { super.writeOutput(); //Display the name


System.out.println("Student Number: " + studentNumber); }
// The class student will behave exactly the same.

**A derived class of a derived class

public class Undergradute extends Student {


private int level; //1 for freshman, 2 for sophomore //3 for junior,
or 4 for senior.
public Undergraduate() {
super();
level = 1
}
public Undergraduate(String initialName, int initialStudentNumber, int
initialLevel) {
super(initialName, initialStudentNumber);
setLevel(initialLevel); //checks 1 <= initialLevel <= 4
}
public void reset(String newName, int newStudentNumber, int newLevel){
reset(newName, newStudentNumber); //Student's reset
setLevel(newLevel); //Checks 1 <= newLevel <= 4
}
public int getLevel() {
return level;
}
public void setLevel(int newLevel) {
if ((1 <= newLevel) && (newLevel <= 4))
level = newLevel;
else {
System.out.println("Illegal level!");
System.exit(0); }
}
public void writeOutput() {
super.writeOutput();
System.out.println("StudentLevel: " + level);
}
public boolean equals(Undergraduate otherUndergraduate) {
return equals(Student)otherUndergraduate) && (this.level ==
otherUndergraduate.level); }
}

An object of the Undergraduate inherits the instance variables that are defined in Student
the derived class of Person and its base class Person.
You cannot use repeated supers, or supers in a chain format
An object can have several types due to inheritance, an object of type undergraduate is an
object of type Student and type Person.
An object of a descendant class can do the same things as an object of an ancestor class.
An object of a class can be referenced by name by a variable of any ancestor type.

Student s = new Student();


Undergraduate ug = new Undergraduate();
Person p1 = s;
Person p2 = ug;

or if you want to bypass the variables use:


Person p1 = new Student();
person p2 = new UnderGraduate();

Student s = new Person(); //ILLEGAL!


Undergraduate ug = new Person(); //ILLEGAL!
Undergraduate ug2 = new Student(); //ILLEGAL!

A student is a Person but a person is not necessarily a Student


If class A has an object of class B as an instance variable , the relationship between A and
B is "has a".

% The keyword super: can be used to call a constructor from the super class
% The keyword super: Can also be used to invoke a method from the super class
**The class Object

The Object class is an ancestor of all classes.


If you define a class and do not make it a derived class of some other class, then java will
automatically make that class a derived class of the Object class.
The class Object does have methods that every class inherits, i.e equals and toString
methods.
These methods are useless for our new derived classes and need to be overrided
println is an example of a real life overloaded method
Another method inherited from the class Object is the method clone. It takes no arguments
and returns the copy of the calling object, the information in the clone object is suppose to
be identical to the original object.

**A Better equals Method for Student class

The (instanceof) operator checks if an object belongs to which class

public boolean equals(Object otherObject){


boolean isEqual = false;
if (otherObject != null) && (otherObject instanceof Student){
Student otherStudent = (Student)otherObject;
isEqual = this.sameName(otherStudent) && (this.studentNumber ==
otherStudent.studentNumber);
}
return isEqual;
}

**Polymorphism

Polymorphism allows you to make changes to the methods in the derived classes and
have those methods apply to the base class.
Consider the Person ,Student an d undergraduate classes

Lets say we we want to set up a committee that consists of 4 people who are either
students or employees.
1. We need to make an array of type Person to accommodate any class derived from it.

Person person = new Person[];


2. Next we need to add objects to the array that represent members of the
committee

person[0] = new Undergraduate("Cotty, Manny",4910,1);


person[1] = new Undergraduate("Kick, Anita",9931,2);
person[2] = new Student("DeBanque, Robin", 8812);
person[3] = new Undergraduate("Bugg, June", 9901, 4);
2. Next we need to output a detailed report containing information about the committee
members. The writeOutput method contains this detail.

person[0].writeOutput();

3. The writeOutput method associated with the class used to create the object is used,
more precisely when an overridden method is invoked, its action is the one defined in
the class used to create the object using the new operator. This is called
**Dynamic/Late binding.

for (Person p; person){


p.writeOutput();
System.out.println();
}

**Demo Polymorphism

public class PolymorphismDemo {


public static void main(String[] args) {
Person[] people = new Person[4];
people[0] = new Undergraduate("Cotty, Manny", 4910, 1);
people[1] = new Undergraduate("Kick, Anita", 9931, 2);
people[2] = new Student("DeBanque, Robin", 8812);
people[3] = new Undergraduate("Bugg, June", 9901, 4);
for (Person p : people) {
p.writeOutput(); /// Even though p is of type Person, the
writeOutput method associated with Undergraduate or Student is invoked
depending upon which class was used too create the object.
System.out.println();
}
}
}

You might also like