Vous êtes sur la page 1sur 46

Lecture4

Object oriented Programming

Java is an object oriented language


Java is an object oriented language. Java, unlike some other languages, is considered as a pure object oriented language as everything in java should be enclosed, basically inside a class. There can be no global variables or functions.

In addition to classes, we can have interfaces as well.

Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm using "objects" to design applications. An object contains both state and behaviour.

State of an object is the current data.


behaviour is implemented as methods.

An object in an OO language can be easily compared to a real world object.

Example
Consider a car.

A car has some properties Like


model fuel type

which are the state (or properties) of that object. Similarly it will also have functions Like

Move right Move left stop

Object-Oriented Principles
Object-Oriented Programming (OOP) has certain important features like

Encapsulation o Inheritance o Polymorphism o Abstraction


o

What makes a programming language an OOP programming language


While there is some disagreement in what actually makes a programming language

an OOP programming language, there are generally three underlying principles that must be supported by any OOP language:
Data encapsulation Inheritance

Polymorphism

Data encapsulation
is concerned with hiding irrelevant information from the users of a class and exposing the relevant. (Data hiding) The primary purpose of data encapsulation is to reduce the level of software development complexity. By hiding the details of what is needed to perform an operation, the use of that operation is simpler.

Data encapsulation

Protect the internal state of an object. Modifications to the object are controlled through the methods. By hiding variables, sharing of information between classes is eliminated.

By hiding the variables that represent the state of an object.

Any changes to the state are verified by the code in the methods.

This reduces the amount of coupling possible in an application.

Data Hiding

We can expose our operations hiding the details of what is needed to perform that operation.
We can protect the internal state of an object by hiding its attributes from the outside world

by making it private
and then exposing them through setter and getter methods. Now modifications to the object internals are only controlled through these methods.

Access Modifiers

Access Modifiers Example

Example
public class student { private String name; public String getName()

{
return name; } public void setName(String name) { this.name=name; } }

public class Customer { private String name; private int accountNumber;

private double balance;


public Customer() { this.name = "Default Customer"; this.accountNumber = 12345;

this.balance = 0.0;
} public String getName() { return name; } public void setName(String name) throws Exception { this.name = name; }

public int getAccountNumber() {

return accountNumber;
} public void setAccountNumber(int accountNumber) { this.accountNumber = accountNumber; } public double getBalance() { return balance; } public void setBalance(double balance)

{
if(balance >0) { this.balance = balance ; } }

public boolean deposit(double amount) {

boolean done = false ;


if(amount <=this.balance) { balance = balance amount ;

done =true ;
} return done ; }

Creating objects
public class CustomerDriver
{
public static void main(String[] args) {
// Define a reference and creates a new Customer object Customer customer; customer = new Customer(); Customer.balance = 5000 ; // Compile time error customer.setBalance(5000); System.out.println(customer.getBalance()); customer.deposite(10000); System.out.println(customer.getBalance()); customer.deposite(4000); System.out.println(customer.getBalance());

Exercise
1. 2.

Create a new class called rectangle The class has a width and height instance variables

3.
4.

Create no argument constructor for the class for initializing the class variables
Define a get area and get perimeter methods

Inheritance and Relationships between Classes

Relationships between classes in Java


The most popular types of relationship between classes are: "is-a" relationship, which represents the inheritance principle. "has-a" relationship that represents composition or aggregation principle.

Inheritance

Describes the relationship between two classes. A class can get some of its characteristics from a parent class and then add unique features of its own. In this case you have a super class (parent class), and a sub-class (child class). The super class will have common attributes and protocols of parent and child. The child class will inherit all attributes and protocols from his parent in addition the sub-class will have its own special attributes or messages which are not found in the parent class.

Class B Inherit From Class A

Class B Inherit From Class A

Java and Inheritance

A class inherit from another class using the word

extends followed by the class name to inherit from

In general, Java supports single-parent, multiple-children inheritance and multilevel inheritance (Grandparent-> Parent -> Child) for classes and interfaces. (Inheritance Tree)

Java supports multiple inheritance (multiple parents, single child) only through interfaces.

Java class can inherit only one class

Exercise
Create a class called Car 2. Car has two attributes color and x 3. Define move right and move left methods 4. Create a class called helicopter 5. helicopter has an instance variable called y 6. Define move up and move down methods 7. Class helicopter inherit from class car 8. Create setter and getter methods and no argument constructor for each of the two classes
1.

Polymorphism
Overriding and overloading

Method overriding

Overriding is defining a method in a subclass with the same name and type signature as a method in its superclass and when this subclass instance appears in the superclass. Occurs between two different classes One of them inherit from the other (Inheritance Relationship)

Same Method Signature but different behavior

Example
In strategy games
When we select a soldier and a tank And press Attack The two types will execute the same command but with different behaviours Soldier soldier = new Soldier(); Tank tank = new Tank();

Tank.attack();
Soldier.attack();

Overloading

A method is said to be overloaded when there are other methods, defined in the same class, or inherited from some superclass, with the same name but a different method signature, i.e. different types and/or numbers or arguments. A same class could have two or more methods with the same name but with different signature (number of arguments, or different types of arguments), this is known as overloading. Note that: a class could not have two or more methods with the same signature.

Overloading applies also on constructors, since we deal constructors as other methods. So a class could have more than one constructor but with different signature.

Example
public Account() { this.holder= " "; this.number=" "; this.balance = 0.0; } //-------------------------------------------------------------public Account(String h, String n, double b) { this.holder = h; this.number = n; this.balance = b; }

Summary

The general strategy when adding new class/methods is to: Reuse existing classes and methods where possible

Overridden methods from the java parent Class

.Equals(Object o)
is used to compare two objects and see if they are equivalent which means that they are belong to same class and have the same current state. Simply means that the two variables refer to same object.

For more information about .equals(Object o) method

http://www.tutorialspoint.com/java/number_equals.htm

.ToString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

For more information about ToString() method

http://www.tutorialspoint.com/java/number_tostring.htm

Abstraction

Abstract Class

Assume a case when two classes have common attributes, and methods, but at the same time each one has its own methods. In this case you could not implement is-a relationship. is a class that contains a common message protocol and common set of attributes for its sub classes. In Java an abstract class cannot be instantiated, which means you could not create an object of abstract class type.

For more information http://www.tutorialspoint.com/java/java_abstraction.htm

Example
public abstract class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { this.name = name; this.address = address; this.number = number; } public String getName() ; public String getAddress() { return address ; } }

Interface

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviours of an object. An interface contains behaviours that a class implements. You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces.

o o o o o o

For more information http://www.tutorialspoint.com/java/java_interfaces.htm

Example
Public interface Animal { public static final int LEGS =4; public void eat(); public void travel(); public void talk(); }

public class Dog implements Animal { public void eat() { System.out.println(Dog eats"); } public void travel() { System.out.println(Dog travels"); } public static int noOfLegs() { return LEGS ; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } }

Static Variables
Static members are members that are not related to each individual object, they are related to all objects ( the class it self).

Defining
Use the keyword static before the member

Usage:
ClassName.staticMemberName
Math.max(a,t); // no math objects needed println(Math.pi);

Static methods can be called only by static methods Static members initialized when class first used and have the application lifetime No static local variables You can also refer to static members using any object created from the class

Examples:

tax variable in Employee class * pi variable in Math class (the constant : 3.14) Object Counter

Packages
For good organization and scoping we use packages for class grouping.
Separate classes with the same name in the same project Good organization Naming packages

e.g. com.sevendash.javacourse.lecture4

Any Questions ?

END

Vous aimerez peut-être aussi