Você está na página 1de 61

Internet Programming And Java MCA-502(N2) MCA-Semester III

Internet Programming And Java


MCA-502(N2)

Object Oriented Programming

Preetinder Singh Brar GJ-IMT 1


Internet Programming And Java MCA-502(N2) MCA-Semester III

OOP Model
• Organization is centered around objects
rather than actions
• Central design of programs is based on
how data is defined and how it can be
manipulated rather than the sequential
logic of the program
• Java embraces this model as the core of
its design

Preetinder Singh Brar GJ-IMT 2


Internet Programming And Java MCA-502(N2) MCA-Semester III

Classes
• Everything in Java is a class (basically)
• A class defines a new data type and all of the properties
that an object of that type contains
– Fields (data members, instance variables, …)
– Methods (procedures to possibly manipulate the fields or provide
some other functionality)
• Each instance of a class has a copy of all non-static
fields and methods defined for that class
– Actually the method code is shared among all instances but
conceptually this is not important
• Only one copy of static fields and methods exists for
each class

Preetinder Singh Brar GJ-IMT 3


1. What are Classes, Objects?

• A class is a factory for objects.


– e.g. a Car class is a factory for Car objects

• A Car class is not a Car object


– e.g. a Car factory is not the Cars it makes

Car
class
Car objects
• A class consists of data and methods.

• Each object gets a copy of the class' data.

• An object uses the methods stored in the c


lass
– the class is a kind of method library for all of its
objects
Internet Programming And Java MCA-502(N2) MCA-Semester III

Revisiting static
• static class members
– can be accessed from outside of its class through the use of the
class name
– can be accessed from inside any member class method with or
without the class name
• static methods
– Do not have access to non-static methods or fields (you will get
a compiler error if you try this)
– Makes sense since static members are not associated with any
particular object and exist even before any object of the class is
instantiated

Preetinder Singh Brar GJ-IMT 6


Internet Programming And Java MCA-502(N2) MCA-Semester III

Initializing data
• Three ways to initialize class member variables
– Right in the class body during variable declaration
class MyClass {
String myVariable = “foo”;
int a = 10;
}

– Initialization blocks (can also be static)


class MyClass {
int myArray[];
{
myArray = new int[10];
for(int i = 0; myArray.length < i++)
myArray[i] = i;
}
}

– Constructors
Preetinder Singh Brar GJ-IMT 7
Internet Programming And Java MCA-502(N2) MCA-Semester III

Constructors
• A constructor is a special method used to initialize class
members with custom specified data during instantiation
• Declared with no return type and a name which is the
same as the class name
class MyClass {
MyClass(..parameters..)
{
//initialize data here
}
}

• If you do not create a constructor, Java automatically


provides one that takes no arguments and does nothing
• If you create any constructor at all (including one with
arguments), the default constructor will not be created
for you
Preetinder Singh Brar GJ-IMT 8
Internet Programming And Java MCA-502(N2) MCA-Semester III

Method Overloading

• Methods with the same name in one class


can be created as long as they have
different parameters
• You can overload constructors just as you
can other methods
• You can call one constructor from another
constructor using the this keyword

Preetinder Singh Brar GJ-IMT 9


Internet Programming And Java MCA-502(N2) MCA-Semester III

Destructors
• No such thing!
• Java has a garbage collector that
automatically cleans up objects that are no
longer referenced in your program
• Each class also has a finalize() method
that is called when the object is garbage
collected
• You probably don’t want to do anything
with it

Preetinder Singh Brar GJ-IMT 10


Internet Programming And Java MCA-502(N2) MCA-Semester III

Packages
• Java has an additional level of support for organizing
your classes called packages
• You can put a class in a package by declaring the
package at the type of the file

package myPackage;
class MyClass {
MyClass(..parameters..)
{
//initialize data here
}
}

• Note: Java is strict with its file and directory naming


conventions and organization. All classes that you put
into a package must reside in a directory with that
package name
Preetinder Singh Brar GJ-IMT 11
Internet Programming And Java MCA-502(N2) MCA-Semester III

Modifiers
• Java has access attributes similar to C++
– No modifier
• Can be accessed by any class in the same package
– public
• Accessible by anyone
– private
• Can be accessed by any methods within the class. Note that this
includes a separate instantiation of the same class
– protected
• Can be accessed by any class in the same package and any
subclass in any package

Preetinder Singh Brar GJ-IMT 12


2.1. What is Inheritance?

• Derive a new class (subclass) from an ex


isting class (base class or superclass).

• Inheritance creates a hierarchy of related


classes (types) which share code and int
erface.
Internet Programming And Java MCA-502(N2) MCA-Semester III

Inheritance
• Sometimes when designing classes we run into the
following relationship
– Class1 is a more specialized form of Class2
• In this situation we do not want to duplicate all of the
functionality and attributes in Class1
• Instead we create Class2 as a subclass of Class1
• Class2 inherits all of the fields and methods provided in
Class1 and can also define additional functionality for its
specialized features

Preetinder Singh Brar GJ-IMT 14


Internet Programming And Java MCA-502(N2) MCA-Semester III

Inheritance
• We declare a class as a subclass of another through the
use of the extends keyword
class SubClass extends BaseClass{

}

• A class can be a subclass of only one other class


• All fields and methods of the base class are inherited by
the subclass
– Private data members of the base class do exist in the subclass
but they are not accessible directly by any method of the
subclass
– Static data members of the base class are also inherited
meaning that the sub class and base class share one copy of
the static members
Preetinder Singh Brar GJ-IMT 15
2.2. Students Example

• Develop a base class called Studen


t

• Use it to define a subclass called G


radStudent
The Class Hierarchy

Student.java
student_id, toString()
year, name year_group()

inherits (extends)

GradStudent.java
dept, toString()
thesis
Objects as Pictures

s1 gs1
student_id 100 student_id 200
year 1 year 4
name “Jane Doe” name “John Smith”

dept “Pharmacy”

thesis “Retail Thesis”


2.3. Superclass References

• It is possible for a superclass reference


(e.g. a Student variable) to be assigned
a subclass object (e.g. a GradStudent obj
ect).
Internet Programming And Java MCA-502(N2) MCA-Semester III

Subclass Constructors
• Constructors of a subclass should always call one of the
constructors of the base class first
• This can be done with the super keyword
class SubClass extends BaseClass{
SubClass() {
super(..arguments..);
}
}

• If you do not call a constructor of the base class, Java


will automatically call the default constructor of the base
class at the beginning of your constructor
• If the base class does not have a default constructor, this
will generate an error

Preetinder Singh Brar GJ-IMT 20


Objects as Pictures

gs1
student_id 200
stud
year 4
name “John Smith”

dept “Pharmacy”

thesis “Retail Thesis”

stud and gs1 refer to the same object.


2.4. Extends and Private
• Studenthas three private variables (studen
t_id, name, year) which are inherited by Grad
Student
– what does this mean?

• Private variables in a superclass cannot b


e directly seen or changed by a subclass.

continued
• This means that methods in the GradStud
ent class cannot directly see or change
student_id, name, or year
– how can they be seen/changed?
• A better object diagram:
student_id 200

year 4
name “John Smith”

dept “Pharmacy”
gs1
thesis “Retail Thesis”

continued
2.5. Protected Variables

• The protected variables of a superclass ca


n be accessed by methods in subclasses
– (and by other classes in the package)
– but they are private to clients/users of the clas
s

– this level of visibility is between public and pr


ivate
Internet Programming And Java MCA-502(N2) MCA-Semester III

Method Overriding
• You can override any method of the base class by
declaring the method in your subclass with the same
signature (same return type, method name, and
parameter list)
• If you have overridden a base class method and wish to
access the base class version of it, you can again use
the super keyword
class SubClass extends BaseClass{

public String baseMethod() {
return super.baseMethod() + “\n”;
}
}

Preetinder Singh Brar GJ-IMT 25


Internet Programming And Java MCA-502(N2) MCA-Semester III

The Object class


• Every class in Java extends one and only one class
(except for one)
• If you don’t specify a base class, your class
automatically extends the Object class
– Every class in Java contains the basic functionality methods
defined in the Object class
– Refer to the Java API for a complete spec on the Object class
• The net result of this design is that Java classes make
up one giant hierarchy with the Object class at the top

Preetinder Singh Brar GJ-IMT 26


Internet Programming And Java MCA-502(N2) MCA-Semester III

Polymorphism
• The power of OOP programming is realized through
polymorphism
• Say we wish to work with a list of user accounts in the
RPI CS department
• We have defined a class called UserAccount with two
subclasses
– StudentUserAccount
– ProfessorUserAccount
• Polymorphism allows us work with a list of UserAccounts
without knowing or caring what type of accounts they are

Preetinder Singh Brar GJ-IMT 27


Internet Programming And Java MCA-502(N2) MCA-Semester III

Polymorphism
• In Java we can assign a variable of a certain class type
an instance of that particular class or an instance of any
subclass of that class
UserAccount myAccount = new StudentUserAccount();

• Now the myAccount variable looks like a UserAccount


object and can be treated exactly like one but under the
hood it is actually a StudentUserAccount object
• We can typecast it back to a StudentUserAccount type if
we ever need the specialized functionality of the
StudentUserAccount class
StudentUserAccount myStudentAccount =
(StudentUserAccount)myAccount;

Preetinder Singh Brar GJ-IMT 28


Internet Programming And Java MCA-502(N2) MCA-Semester III

Dynamic Type Checking!


• Java has support for dynamic type checking which is the
true power of polymorphism
• Example:
– UserAccount has a method named privileges() which returns a
list of privileges associated with that account
– StudentUserAccount and ProfessorUserAccount each have
overridden the privileges() method with their own specialized
functionality
– A UserAccount variable instantiated with a StudentUserAccount
object calls the privileges() method
– At run-time, Java checks the type of this object and sees that it
is a StudentUserAccount and therefore calls the
StudentUserAccount version of the privileges() method instead
of the UserAccount version

Preetinder Singh Brar GJ-IMT 29


3.1. Dynamic Binding

• There are several computer-related


meanings of polymorphism. The on
e we are using is:
– dynamic binding
– it says that the method used by an obj
ect call ( e.g. stud.toString() ) is de
cided at run time
Dynamic Binding Example

Student stud;
GradStudent g;
PostGradStudent p;
:
stud = new Student();
stud.toString(); // which toString()?

val = // some input number


if (val == 1)
stud = g;
else
stud = p;
stud.toString(); // which toString()?
• The toString() method used by stud will va
ry over time
– initially it will be the one in Student
– later, depending on the value of val, it will be t
he method in GradStudent or PostGradStuden
t
Internet Programming And Java MCA-502(N2) MCA-Semester III

Abstract classes
• You can declare a class abstract with the abstract
keyword
public abstract class Animal {
public abstract void sound();
public Animal(String type) {
this.type = type;
}
public String toString() {
return “This is a “ + type;
}
private String type;
}

• Abstract classes provide a prototype but not an


implementation for some of its methods because the
context of the implementation is only important in
subclasses

Preetinder Singh Brar GJ-IMT 33


Internet Programming And Java MCA-502(N2) MCA-Semester III

Abstract classes

• Are intended to be base classes


• Cannot be instantiated
• You can declare variables of an abstract
class type but they can only be assigned
instantiations of a subclass of the abstract
class

Preetinder Singh Brar GJ-IMT 34


3.2. Abstract Classes

• An abstract class may be missing impleme


ntations for some of its methods
• they must be implemented by the subclasses

• The abstract class specifies the method int


erfaces (the names, argument types), and
leaves subclasses to implement them
– it is an interface guide
3.3. Employees Example

abstract
Employee

extends

Boss Hourly
Worker
Commission
Piece
Worker
Worker
Notes
• Employee is an abstract class
– it contains no implementation for its ear
nings() function
– each subclass must implement it

• Later in Test.java, an Employee referen


ce will be used to manipulate Boss, Co
mmissionWorker, PieceWorker, and Hourl
yWorker objects.
Internet Programming And Java MCA-502(N2) MCA-Semester III

3.4. Nested Classes

• An nested class is a class that is defined


inside another class.
• To this point we have only studied top-
level classes.
– at most one public per file
– arbitrarily man package-scope per file
– either package or public ONLY
• Nested classes introduced in jdk1.1

Preetinder Singh Brar GJ-IMT 38


Internet Programming And Java MCA-502(N2) MCA-Semester III

Why use nested classes?


• Simplifies many coding tasks
– can define small classes on the fly near the
objects created from them + concise syntax
– can access outer classes iv’s automatically –
no need to pass a this pointer to the
constructor of separate outer class
– can be hidden from other classes in the same
package
• However, price to pay in terms of
complexity, number of gotchas, etc.

Preetinder Singh Brar GJ-IMT 39


Internet Programming And Java MCA-502(N2) MCA-Semester III

Pre jdk1.1
• In jdk1.0, the clean and simple class rules were
ballyhooed as a major improvement over C++
• Addition of inner classes complicates things
significantly
• However, they do make certain code much less
awkard to write, particularly when writing GUIs
• Still, you do not have to use them, but they can
be quite cool and I do recommend it in
moderation!

Preetinder Singh Brar GJ-IMT 40


Internet Programming And Java MCA-502(N2) MCA-Semester III

Types of nested classes

• Inner classes
– local
• anonymous or named
– non-local
• named only
• Static nested classes
– non-local named only

Preetinder Singh Brar GJ-IMT 41


Internet Programming And Java MCA-502(N2) MCA-Semester III

Non-local inner classes


• Simply a nested class that does not have the
static attribute and is not defined within a class
method.
• Can be private, public, package, protected,
abstract, etc. just like any class member.
• Think of outer class as owning inner class – inner
class can only be instantiated via outer class
reference (including this)
• Inner class has access to all outer class iv’s,
private or otherwise!

Preetinder Singh Brar GJ-IMT 42


Internet Programming And Java MCA-502(N2) MCA-Semester III

Simple non-local inner class


example
class Outer{
private int x1;
Outer(int x1){
this.x1 = x1;
}
public void foo(){ System.out.println(“fooing”);}
public class Inner{
private int x1 = 0;
void foo(){
System.out.println(“Outer value of x1: “ + Outer.this.x1);
System.out.println(“Inner value of x1: “ + this.x1);
}
}
Preetinder Singh Brar GJ-IMT 43
Internet Programming And Java MCA-502(N2) MCA-Semester III

Simple example, cont -- driver

• Rules for instantiation a little funny

public class TestDrive{


public static void main(String[] args){
Outer outer = new Outer(); // can create in regular way
Inner inner = outer.new Inner(); //must call new through
//outer object handle
inner.foo();
// note that this can only be done if inner is visible
// according to the regular scoping rules
}
}
Preetinder Singh Brar GJ-IMT 44
Internet Programming And Java MCA-502(N2) MCA-Semester III

When to use non-local inner classes


• Most typically used when inner class is
instatiated from outer class.
• If classes naturally “belong together”, it is
cumbersome to pass a this pointer to a separate
outer class just so second class can access first
class’s properties/methods.
• Note that inner class can access outer class’s
private data, making them even more powerful
than mechanism implied above!

Preetinder Singh Brar GJ-IMT 45


Internet Programming And Java MCA-502(N2) MCA-Semester III

Local inner classes


• Inner classes may also be defined within class
methods.
• These are called local inner classes.
• Principle advantage is scoping: such classes are
completely inaccessible anywhere but the method
itself where they are defined.
• Thus, they have no visibility attribute (public, etc.)
• Also, can NOT access local variables other than
those declared with final attribute.

Preetinder Singh Brar GJ-IMT 46


Internet Programming And Java MCA-502(N2) MCA-Semester III

Local anonymous inner classes


• Local inner classes can be taken a step
further – it is not required to give them an
explicit name.
• This is very convenient when you want to
use a class only once and the code that it
contains is succinct.
• Great example is defining Swing callback
functions.

Preetinder Singh Brar GJ-IMT 47


Internet Programming And Java MCA-502(N2) MCA-Semester III

Anonymous class example


but.addActionListener(
new ActionListener(){
public void actionPerformed(actionEvent ae){
//do work here
}
}
);

Preetinder Singh Brar GJ-IMT 48


3.5. Polymorphic Data Structure
s
• Normal data structures (e.g. int a[]) can on
ly hold one type of thing (e.g integers).

• A polymorphic data structure can hold differ


ent types of objects
– the coding technique is to build the data structur
e using a superclass type
– it can then hold objects of the subclass types
Internet Programming And Java MCA-502(N2) MCA-Semester III

Interfaces
• Takes the abstraction one step further
• Only defines a set of methods that represent the class
interface but does not provide an implementation
• Can also define constants
public interface Shape {
double PI = 3.14;
int Area();
String name();
}

• All methods of an interface are automatically public and


abstract so you do not need to explicitly specify this

Preetinder Singh Brar GJ-IMT 50


Internet Programming And Java MCA-502(N2) MCA-Semester III

Interfaces
• Java provides support for pseudo-multiple-inheritance
through the use of interfaces
– Classes can extend one and only one class
– However, classes can implement any number of interfaces

public class Circle implements Shape {



}
• A class that implements an interface must provide an
implementation for each method defined in the interface
• If a class implements more than one interface that have
identical methods, one implementation of the method is
sufficient as long as the return type is the same in both
interfaces
Preetinder Singh Brar GJ-IMT 51
Internet Programming And Java MCA-502(N2) MCA-Semester III

Interfaces

• Polymorphism can be used with interfaces


too!
• Example
– From the previous slide we can create a
variable of type Shape
– We can then assign this variable an
instantiation of the Circle class
• Interfaces cannot be instantiated (clearly)

Preetinder Singh Brar GJ-IMT 52


Notes
• Employee is an abstract class
– it contains no implementation for its ear
nings() function
– each subclass must implement it

• Later in Test.java, an Employee referen


ce will be used to manipulate Boss, Co
mmissionWorker, PieceWorker, and Hourl
yWorker objects.
4. Interfaces

• An interface is a class containing no variab


les and no method implementations.

• An interface normally only contains metho


d declarations:
public interface Shape {
public abstract double area();
public abstract double volume();
public abstract String getName();
}
implements

• A class implements an interface by implem


enting all of its methods.

public class Point implements Shape {


protected int x, y;

public Point() { x = 0; y = 0; }
:
// various methods
:

continued
Multiple Implements

• A class can implement several interfaces, t


o get a simple form of multiple inheritance:
public class nokia
implements phone, browser {
:
}

continued
• Java does not have multiple inheritance
using extends, so interfaces are used in
stead.

• An interface is a guide
– it says what methods a subclass should im
plement in order to conform to the supercla
ss
Internet Programming And Java MCA-502(N2) MCA-Semester III

Factory Creation Pattern


• Problem:
– You want to write an application that supports the native look
and feel of multiple GUI systems such as Windows and Mac
– You don’t want to rewrite your code for each system
• Solution:
– Define a common interface for using either interfaces or abstract
classes for each GUI element that you wish to use
– Define a concrete subclass of each GUI element for each
windowing system that you wish to support
– Your application works directly with the abstract class interface
and does not know or care what type of object it is using

Preetinder Singh Brar GJ-IMT 58


Internet Programming And Java MCA-502(N2) MCA-Semester III

Factory Creation Pattern

Button Application works directly


with the abstract classes
MacButton WindowsButton

Objects are instantiated using


the concrete subclasses.
Menu

MacMenu WindowsMenu

Question: How can we work only with the abstract classes if we must
instantiate them using one of the concrete subclasses?

Preetinder Singh Brar GJ-IMT 59


Internet Programming And Java MCA-502(N2) MCA-Semester III
public interface WidgetFactory {
Answer: Factories Button newButtonInstance();
Menu newMenuInstance();
}

public class WindowsWidgetFactory implements WidgetFactory {


public Button newButtonInstance()
{
return new WindowsButton();
}
public Menu newMenuInstance()
{
return new WindowsMenu();
}
}

public class MacWidgetFactory implements WidgetFactory {


public Button newButtonInstance()
{
return new MacButton();
}
public Menu newMenuInstance()
{
return new MacMenu();
}
}

Preetinder Singh Brar GJ-IMT 60


Internet Programming And Java MCA-502(N2) MCA-Semester III

Factory Creation Pattern


• Using the factories, you can instantiate your objects without even
knowing which subclass of the abstract class you’re instantiating!

public class FactoryTest {


public static void main(String[] args)
{
WidgetFactory factory = new WindowsWidgetFactory();
//WidgetFactory factory = new MacWidgetFactory();

Button myButton = factory.newButtonInstance();


Menu myMenu = factory.newMenuInstance();
}
}

Preetinder Singh Brar GJ-IMT 61

Você também pode gostar