Vous êtes sur la page 1sur 44

CHAPTER 1: CLASS AND OBJECT

BCS1223: DATA STRUCTURES & ALGORITHMS

CHAPTER OBJECTIVE

To review:
Basics of Java programming
Object-oriented programming

JAVA PROGRAMMING

HELLO WORLD!

GETTING STARTED
In Java, executable statements are placed in methods, that belong
to class definitions
Main method the first method to be executed when running a
Java program.
Program block any set of statements between the braces {
and }
Identifier name of a class, method, or variable in Java.Any string
of characters that begin with a letter, and can consists of letters,
numbers, and underscore characters.
// This is an inline comment.
/*
* This is a block comment.
*/

VARIABLE DECLARATIONS
Each variable must be declared before use in program.
Variable name can consist of letters, digits, underscores,
and dollar signs.
Java is case sensitive.

variable n variable N

There are three kinds of variables in Java:

Local variables

Declared in methods, constructors, or blocks.

Local variables must be initialized before use.

Access modifiers cannot be used

Instance variables
Class/static variables

VARIABLE DECLARATIONS

Primitive data types: boolean, char, byte, short, int, long,


float, double

Examples:

int a, b, c; // Declares three ints, a, b, and c.


int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a

Reference data types

OPERATORS
Assignment operator

int gear = 1;
x = y = z = 1; byte B = 22;

Arithmetic operators

+
*
/
%

additive operator (also used for String concatenation)


subtraction operator
multiplication operator
division operator
remainder operator

Compound assignments: +=, -=, *=

OPERATORS
Unary operators

+ Unary plus operator


- Unary minus operator
++ Increment operator
-- Decrement operator
! Logical complement operator

Prefix and postfix operators

class Operator {
public static void main(String[] args){
int var=5;
System.out.println(var++);
System.out.println("\n"+ ++var);
}
}
9

OPERATORS

The Equality and Relational Operators

==
!=
>
>=
<
<=

equal to
not equal to
greater than
greater than or equal to
less than
less than or equal to

Conditional Operators

10

&& Conditional-AND
|| Conditional-OR

OPERATOR PRECEDENCE

11

CASTING

Casting is an operation that allows us to change the type of a value.

Examples:

12

double d2 = 3.9999;
int i2 = (int) d2;
double d3 = (double) i2;

String s1 = "2014";
int i1 = Integer.parseInt(s1);
int i2 = 35;
String s2 = Integer.toString(i2);

// i2 gets value 3
// d3 gets value 3.0

// i1 gets value 2014


// s2 gets value -35

DECISION STATEMENTS

If statement
If else statement
If...else if...else statement
Nested if...else statement
public class Test {

public static void main(String args[]){


int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}

13

DECISION STATEMENTS

Switch statement
switch(grade) {
case 'A' :

System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
14

LOOPS

while Loop
do...while Loop
for Loop
enhanced for Loop

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );

int [ ] numbers = {10, 20, 30, 40, 50};


for(int x : numbers ) {
System.out.print( x );
System.out.print("\n");
}

15

for(int x = 10; x < 20; x = x+1) {


System.out.print("value of x : " + x );
System.out.print("\n");
}

SIMPLE OUTPUT

The System.out object is an instance of the


java.io.PrintStream class that performs output to the
standard output device.

Example:
System.out.print("Java values: ");
System.out.print(3.1416);
System.out.print(',');
System.out.print(15);
System.out.println(" (double,char,int).");

16

SIMPLE INPUT

The System.in object is an object associated with the


standard input device. A simple way of reading input with
this object is to use it to create a Scanner object, using
the expression.
Example:
public class InputExample {
public static void main(String[ ] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your age in years: ");
double age = input.nextDouble( );
System.out.print("Enter your maximum heart rate: ");
double rate = input.nextDouble( );
double fb = (rate age) * 0.65;
System.out.println("Your ideal fat-burning heart rate is " + fb);
}
}
17

EXCEPTION HANDLING

Java throws an exception if an error is detected during


execution of a program.
Catching an error is possible using a try-catch statement
try{
int a[ ] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch(Exception e){
System.out.println("Exception thrown :" + e);
}.

18

EXERCISE
1.

2.

3.

19

Write a program called CheckPassFail which prints


"PASS" if the int variable "mark" is more than or equal
to 50; or prints "FAIL" otherwise.
Write a program called CheckOddEven which prints
"Odd Number" if the int variable number is odd, or
Even Number otherwise.
Write a short Java method that takes an integer n and
returns the sum of the squares of all positive integers
less than or equal to n.

OBJECT-ORIENTED PROGRAMMING

20

OBJECT TECHNOLOGY

Objects are reusable software components that model


items in the real world, such as windows cars,
vehicles, and so on
Object technology is a packaging scheme that enables
programmers to create meaningful software units.
Object-Oriented Programming tends to produce
software that is more understandable, better
organized, and easier to maintain, modify and debug.

21

OBJECT TECHNOLOGY

There are date objects, time objects, paycheck objects,


invoice objects, automobile objects, audio objects,
video objects, file objects, and so on.
On your computer screen, there are button objects,
textbox objects, menu objects and many more. Almost
any noun can be represented as a software object.
Objects have attributes (also called properties or
fields), such as color, size and speed; and perform
actions (also called methods or behaviors), such as
moving, sleeping or drawing.

22

OBJECT TECHNOLOGY

Classes are types of related objects.


A class specifies the general format of its objects, and
the attributes and actions of an object depend on its
class.
An object is related to its class in much the same way
as a building is related to its blueprint.
Contractors can build many buildings from the same
blueprint. Programmers can instantiate many objects
from one class.
With object technology, properly designed classes can
be reused on future projects.
23

OBJECT MODEL

Object => Noun

Attribute => Adjective

Color of a Form

Method => Verb

Form and Controls

Move a Form

Class => Template to create new object

24

Each object created is an Instance of a Class

OBJECT MODEL ANALOGY

Class = automobile
Attributes = make, model, color, year
Object = each individual car

Object is also an Instance of the automobile class

Methods = start, stop, speedup, slowdown

25

OBJECT-ORIENTED CONCEPTS

Java provides explicit support for many of the fundamental ObjectOriented Concepts. Some of these are:
Classification: Grouping related things together. This is supported
through classes, inheritance & packages.
Encapsulation: Representing data and the set of operations on the
data as a single entity - exactly what classes do.
Information Hiding: An object should be in full control of its data,
granting specific access only to whom it wishes.
Inheritance: Java allows related classes to be organized in a hierarchical
manner using the extends keyword.
Polymorphism: Same code behaves differently at different times
during execution.This is due to dynamic binding.

26

OBJECT TECHNOLOGY CONCEPTS

27

REFERENCE VARIABLE
poland
"Poland"
40000000

Country poland = new Country();


Country brazil = new Country();

120359
.5
"Germany"

brazil
"Brazil"
180000000
3287951
1
"USA"

ACCESS MODIFIER
Mode of access
same class
same package subclass
same package non-subclass
different package subclass
different package non-subclass

private

protected

no modifier
( C++)

public

yes
no
no
no
no

yes
yes
yes ( C++)
yes
no

yes
yes
yes
no
no

yes
yes
yes
yes
yes

CLASS & OBJECT IN CODING


public class Country {
private String name;
private long population;
private double area;
private double loan;
private String sender;
public double density() {
return area/population;
}
public void internationalLoan(double ln, String from) {
loan = ln;
sender = from;
}
. . . . . . .
}
public class Countries {
Country poland = new Country();
Country brazil = new Country();
. . . . . . .
}

Attributes
/instance
variables

methods

objects

ADVANTAGES OF OBJECT-ORIENTATION.

A number of advantages can be derived as a result of these object-oriented


features. Some of these are:
Reusability: Rather than endlessly rewriting same piece of code, we
write it once and use it or inherit it as needed.
Extensibility: A class can be extended without affecting its users
provided the user-interface remains the same.
Maintainability: Again, once the user-interface does not changed, the
implementation can be changed at will.
Security: Thanks to information hiding, a user can only access the
information he has been allowed to access.
Abstraction: Classification and Encapsulation allow portrayal of realworld problems in a simplified model.

31

INHERITANCE

Suppose we have the following Employee class:


class Employee {
protected String name;
protected double payRate;
public Employee(String name, double payRate)
this.name = name;
this.payRate = payRate;
}
public String getName() {return name;}
public void setPayRate(double newRate) {
payRate = newRate;
}
public double pay() {return payRate;}
public void print() {
System.out.println("Name: " + name);
System.out.println("Pay Rate: "+payRate);
}
}
32

INHERITANCE

Now, suppose we wish to define another class to represent a


part-time employee whose salary is paid per hour. We inherit
from the Employee class as follows:
class HourlyEmployee extends Employee {
private int hours;
public HourlyEmployee(String hName, double hRate) {
super(hName, hRate);
hours = 0;
}
public void addHours(int moreHours) {hours += moreHours;}
public double pay() {return payRate * hours;}
public void print() {
super.print();
System.out.println("Current hours: " + hours);
}
}

33

NOTES ABOUT INHERITANCE

We observe the following from the examples on inheritance:

Methods and instance variables of the super class are inherited by subclasses,
thus allowing for code reuse.

A subclass can define additional instance variables (e.g. hours) and additional
methods (e.g. addHours).

A subclass can override some of the methods of the super class to make them
behave differently (e.g. the pay & print)

Constructors are not inherited, but can be called using the super keyword. such
a call must be the first statement.

If the constructor of the super class is not called, then the complier
inserts a call to the default constructor -watch out!

super may also be used to call a method of the super class.

34

ABSTRACT CLASS

Inheritance enforces hierarchical organization, the benefit of which are:


reusability, type sharing and polymorphism.

Java uses Abstract classes & Interfaces to further strengthen the idea of
inheritance.

To see the role of abstract of classes, suppose that the pay method is not
implemented in the HourlyEmployee subclass.

Obviously, the pay method in the Employee class will be assumed, which
will lead to wrong result.

One solution is to remove the pay method out and put it in another
extension of the Employee class, MonthlyEmployee.

The problem with this solution is that it does not force subclasses of
Employee class to implement the pay method.

35

ABSTRACT CLASS

The solution is to declare the pay method of the Employee class as


abstract, thus, making the class abstract.
abstract class Employee {
protected String name;
protected double payRate;
public Employee(String empName, double empRate) {
name = empName;
payRate = empRate;
}
public String getName() {return name;}
public void setPayRate(double newRate) {payRate = newRate;}
abstract public double pay();
public void print() {
System.out.println("Name: " + name);
System.out.println("Pay Rate: "+payRate);
}
}
36

ABSTRACT CLASS

The following extends the Employee abstract class to get MonthlyEmployee


class.

class MonthlyEmployee extends Employee {


public MonthlyEmployee(String empName, double empRate) {
super(empName, empRate);
}
public double pay() {
return payRate;
}
}

The next example extends the MonthlyEmployee class to get the


Executive class.

37

ABSTRACT CLASS
class Executive extends MonthlyEmployee {
private double bonus;
public Executive(String exName, double exRate) {
super(exName, exRate);
bonus = 0;
}
public void awardBonus(double amount) {
bonus = amount;
}
public double pay() {
double paycheck = super.pay() + bonus;
bonus = 0;
return paycheck;
}
public void print() {
super.print();
System.out.println("Current bonus: " + bonus);
}
}
HourlyEmployee
Employee

MonthlyEmployee
Executive

38

ABSTRACT CLASS

The following further illustrates the advantages of organizing classes using


inheritance - same type, polymorphism, etc.
public class TestAbstractClass {
public static void main(String[] args) {
Employee[] list = new Employee[3];
list[0] = new Executive("Jarallah Al-Ghamdi", 50000);
list[1] = new HourlyEmployee("Azmat Ansari", 120);
list[2] = new MonthlyEmployee("Sahalu Junaidu", 9000);
((Executive)list[0]).awardBonus(11000);
for(int i = 0; i < list.length; i++)
if(list[i] instanceof HourlyEmployee)
((HourlyEmployee)list[i]).addHours(60);
for(int i = 0; i < list.length; i++) {
list[i].print();
System.out.println("Paid: " + list[i].pay());
System.out.println("*************************");
}
}
}

The Program Output

39

INTERFACE

Interfaces are not classes, they are entirely a separate entity.

They provide a list of abstract methods which MUST be implemented by a


class that implements the interface.

Unlike abstract classes which may contain implementation of some of the


methods, interfaces provide NO implementation.

Like abstract classes, the purpose of interfaces is to provide organizational


structure.

More importantly, interfaces are here to provide a kind of "multiple


inheritance" which is not supported in Java.

If both parents of a child implement a method, which one does the child
inherits? - Multiple inheritance confusion.

Interfaces allow a child to be both of type A and B.

40

INTERFACE

Recall that Java has the Comparable interface defined as:


interface Comparable {
int compareTo(Object o);
}

Recall also that java has the java.util.Arrays class, which has a sort method
that can sort any array whose contents are either primitive values or
Comparable objects.
Thus, to sort our list of Employee objects, all we need is to modify the
Employee class to implement the Comparable interface.
Notice that this will work even if the Employee class is extending another
class or implementing another interface.
This modification is shown in the next page.
41

INTERFACE
abstract class Employee implements Comparable {
protected String name;
protected double payRate;
public Employee(String empName, double empRate)
name = empName;
payRate = empRate;
}
public String getName() {return name;}
public void setPayRate(double newRate) {
payRate = newRate;
}
abstract public double pay();
public int compareTo(Object o) {
Employee e = (Employee) o;
return name.compareTo( e.getName());
}
}

HourlyEmployee
Comparable

42

Employee

MonthlyEmployee

Executive

EXERCISE
1.

43

Type out the program that represent the following class:

EXERCISE

What is the Output?

44

Vous aimerez peut-être aussi