recent

Sailing with Object Oriented Programming

Inheritance
• Software reusability
• Create new class from existing class
Absorb existing class’s data and behaviors
Enhance with new capabilities
• Allows creation of hierarchical classifications.
• It involves
– Generalization
• Creation of general class that defines attributes
common to set of related classes
– Specialization
• Generalized class is inherited by other, specific classes,
each adding attributes unique to it
• Behaviors inherited from superclass
• Additional behaviors
Class, that is inherited -> superclass (parent)
Class, that inherits -> subclass (child) 


SubClass
Specialized version of superclass
• Inherits (almost) all of the instance variables
and methods defined in superclass
• Can add its own unique variables and
methods 

“is-a” vs. “has-a”
“is-a”
– Inheritance
– subclass object treated as superclass object
– Example: Car is a vehicle
• Vehicle properties/behaviors also car properties/behaviors

“has-a”
– Composition
– Object contains one or more objects of other classes
as members
– Example: Car has a steering wheel 
• Object of one class “is an” object of another class
– Example: Rectangle is quadrilateral.
• Class Rectangle inherits from class Quadrilateral
• Quadrilateral: superclass
• Rectangle: subclass
• Superclass typically represents larger set of
objects than subclasses
– Example:
• superclass: Vehicle
– Cars, trucks, boats, bicycles, …
• subclass: Car
– Smaller, more-specific subset of vehicles 

Inheritance
• Keyword extends is used to specify inheritance
class A {
int i=10, j=20;
void printij()
{
System.out.println(i +" "+ j);
}
}
class B extends A {
// specialized features

Example 
class A {
int x;
int y;
A() {
x=0; y=5;
}
void set(int p, int q){
x=p; y=q;
}
void Show(){
System.out.println("X="+x+"\nY="+y);
}
}

public class B extends A{
int z;
B(){
z = 10;
}
void display(){
Show();
System.out.println("Z="+z);
}

The Test Class
public class Driver {
public static void main(String args[]) {
B x = new B();
x.Show();
x.set(8,9);
x.display();
}
}
OUTPUT:
X=0
Y=5
X=8
Y=9
Z=10 

Multilevel Inheritance
• Hierarchy of inheritance
• As many inheritance levels as needed
• Example: 

classes A,B,C,D where D is a subclass of C, which is a subclass of B, which is a subclass of A,Each subclass inherits attributes of all of its superclasses 
• Class hierarchy 
 Direct superclass
Inherited explicitly (one level up hierarchy)
--ndirect superclass
Inherited two or more levels up hierarchy
Single inheritance
 Inherits from one superclass
 Multiple inheritance 
 Inherits from multiple superclasses  
Multilevel Inheritance Example
class A{

}
class B extends A{

}
class C extends B{

}
class D extends C{

}
 
• Subclass inherits attributes from more than 1
superclasses
• Java does not support multiple inheritance
through classes
• It is supported through Interface
 
Super/sub References
• Superclass references can refer to subclass
objects
– Super Ref -> Sub Obj (OK)
– Sub Ref -> Super Obj (Wrong)
Type of the reference determines what members
can be accessed
Super Ref -> Sub Obj
– Can access only the parts defined in superclass
– Reason: super class has no knowledge of subclass’s
added functionalities

Super()
• To invoke the super class’s
– Constructor
– Method
– Variables
• Must be the first statement of the sub-class’s
Constructor
• Constructors are called in the order of
derivation
– From Super to Sub 
• Super is the first statement during the class
– Hence, the order will be same whether or not
super is used
• If super() not used -> default parameter-less
constructors of each super-class will be called 

Other use of super
• To refer to super-class members
• General form:
– super.member
– <member> could be a method or a variable
– super.method() || super.variable
• Suitable for the situations where sub-class
hides members of super by declaring
members of the same name

Example revisited 
class A {
int x;
int y;
A() {
System.out.println("inside A");
x = 0; y = 5;
}
void set(int p, int q){
x=p; y=q;
}
void Show(){
System.out.println("X="+x+"\nY="+y);
}
}

public class B extends A{
int z;
B(){
System.out.println("inside B");
z = 10;
}
void display(){
Show();
System.out.println("Z="+z);
}
}

The Test Class
public class testing {
public static void main(String args[]) {
B x = new B();
x.Show();
x.set(8,9);
x.display();
}
}
OUTPUT:
inside A
inside B
X=0
Y=5
X=8
Y=9
Z=10

Another example 
public static void
main(String [] args){
D obj = new D();
}
class A{
int x;
int y;
A() {
System.out.println("A constructor");
}
}
class B extends A{
B() {
System.out.println("B constructor");
}
}
class C extends B{
C() {
System.out.println("C constructor");
}
}
class D extends C{
D() {
System.out.println("D constructor");

OUTPUT:
A constructor
B constructor
C constructor
D constructor

Modification of constructor
Defined
D() {
System.out.println("D constructor");
}
 
Modified by compiler
D() {
super();
System.out.println("D constructor");





Overloading
• Like constructor overloading
• We can overload methods
– Should have different parameters
– may or may not have different return type
– Should have same name
– Should be in the same scope

Overriding
• Dynamic polymorphism
• Method in super-class re-defined in subclass
• Method should have Same Name and
Signature
• When called within subclass, it will always
refer to the overridden version defined in the
subclass
• Works only when name and signature are
exactly identical
Constructors can not be overridden or
inherited

Example
class A // Super class
{
void disp( )
{
System.out.println(“in class A”);
}
}
class B extends A //Sub class
{
void disp( )
{
System.out.println(“in class B”) // output
}
}
class Main
{
public static void main(String args[])
{
B b = new B();
b.disp();
}
}

More about Overriding
• Call to an overridden method is resolved at
run-time, rather than at compile-time
• This is known as Dynamic Polymorphism
• Overloading is Static Polymorphism
 

Dynamic Method Dispatch
• call to an overridden method is resolved at
run-time
• run-time polymorphism or late-binding
• Super class reference variable can store subclass
objects 

class Main
{
public static void
main(String args[])
{
A obj = new B();
obj.disp();
}

• When an overridden method is called through
a super class reference, Java determines which
version of that method to execute based upon
the type of the object being referred
• The type of object being referred to(Not the
type of reference variable) determines which
version of method to be called

Upcasting and Downcasting
• A subclass reference can be assigned to
superclass reference
• Upcasting is automatic. You need not use
explicit typecast 
 

A obj_a =new A();
B obj_b=new B() ;
A obj_a =obj_b;

 Downcasting
• Casting the references of superclass type to
subclass type is called as downcasting
• Downcasting is not automatic
• Explicit typecast is required
• Compiler verifies that an inheritance relationship
exists between the source and destination
reference types
• However, cast can be invalid at runtime. In such a
case, ClassCastException is thrown 


• 1
Cat c = new Cat();
Animal a = c;
• 2
Animal a = new Animal();
Cat c = (cat) a;
• 3
Animal a = new Cat();
Cat c = (cat) a;
• 4
Cat c = new Cat();
Dog d = (dog) c;

Visibility
Private and Public

class Person {
private String name;
private double height;
}
class Worker extends Person {
void print() {
System.out.println(“Worker” +

name+ “ ” + height);//name and  height Not visible
}
}

• Public
– Always Accessible
• Private
– Accessible within the class
Protected
– Accessible within the class and its subclasses

Methods in the SAME CLASS  Method of SUB-CLASS  Method of any OTHER CLASS
Private                       T
Protected                   T                               T
Public                         T                               T                                        T 


Access Modifiers
• Static
• Final
• Volatile
• Native 
• Transient
• Abstract 
• Synchronized 
 
Static
• It is possible to create a member that can be
used without reference to a specific instance
• When declared as static, it can be accessed
before any objects of that class are created
• Both methods and variables can be declared
as static
• main () method is static because it is called
before any object exists

Static Variables -
• When objects of its class are declared, no copy
of static variables is made
• all instances of the class share the same static
variables
• All the static variables are initialized to their
default values

Example
public class Stuff {
public static String name = "I'm a static variable";
}
public class Application {
public static void main(String[] args) {
System.out.println(Stuff.name);
}
}
I'm a static variable

Static Methods• Can call only other static methods
• Must access only static attribute
• Cannot refer to super or this
• Can be invoked in two ways
– Class.method()
– Object.method()
 

Example
public class StaticMethodExample {
public static void main(String[] args) {
int result = MathUtility.add(1, 2);
System.out.println("(1+2) is : " + result);
}
}
class MathUtility{
int result;
public static int add(int first, int second) {
result = first +second; return result;
}
}
 

public class StaticMethodExample {
public static void main(String[] args) {
int result = MathUtility.add(1, 2);
System.out.println("(1+2) is : " + result);
}
}
class MathUtility{
int result;
public static int add(int first, int second) {
result = first +second; return result;
}
}

public class StaticMethodExample {
public static void main(String[] args) {
int result = MathUtility.add(1, 2);
System.out.println("(1+2) is : " + result);
}
}
class MathUtility{
public static int add(int first, int second) {
return first + second;
}
}

Final
• 3 uses of “final”
– Final variable
– Final method
– Final class

Final variable
• Equivalent to constant
• Must be initialized during the declaration
• Cannot be re-initialized
 
• Blank final variable possible, BUT
– Should be initialized in Constructor
• E.G.
– final int A = 20; A =30; //wrong
– final int A; A =30; //OK 

Final method
• Final method cannot be overridden
• Final method can be overloaded
• Since final methods are not overridden, call to
such methods is resolved at compile time
(Early binding)
• Methods called from constructors should
generally be declared final

Final class
• Final class cannot be inherited.
• Final class can be instantiated.
• Declaring a class as final implicitly declares all
its methods as final too.
• Particularly useful when creating an
immutable class, like String

Volatile
• During execution, compiled code might cache the
values of fields for efficiency reasons
• Multiple threads can access the same field
– It is vital that caching is not allowed to cause
inconsistencies when reading and writing the value
• The volatile modifier can be used to
– Inform the compiler that it should not attempt to
perform optimizations on the field
– To avoid unpredictable results when the field is
accessed by multiple threads 

Java Object
• java.lang.Object
• All classes are subtypes of Object

class Person extends Object {
String name;
double height;
}
class Worker extends Person {
void print() {
System.out.println(“Worker” +
name+ “ ” + height);
}
}

• java.lang.Object
• All classes are subtypes of Object
class Person extends Object { //Implicitly
String name;
double height;
}
class Worker extends Person {
void print() {
System.out.println(“Worker” +
name+ “ ” + height);
}
• Each instance can be seen as an Object
instance
• Object defines some services (methods) which
are useful to all classes

Object  
toString():String
equals(object):boolean 

• public String toString()
– Returns a string that "textually represents" this
object
– It is recommended that all subclasses override this
method
– The output should be a concise but informative
representation
– for class Object it returns :
getClass().getName() + '@' +
Integer.toHexString(hashCode())

• public boolean equals(Object obj)
– Returns whether obj is “equal to” this one
– Reflexive
• x.equals(x) should return true
– Symmetric
• x.equals(y) should return true if and only
if y.equals(x) returns true
– Transitive
• if x.equals(y) returns true and y.equals(z) returns true,
then x.equals(z) should return true
– Consistent
• x.equals(y) consistently return true or consistently
return false, provided none of the objects are modified

• Other Methods
– protected Object clone()
• Creates and returns a copy of the object
– public int hashCode()
• Returns the hash code of the object
– protected void finalize()
• Called by the garbage collecotor

Abstract 
Abstract Classes
• Superclass is used to define common behavior
of many child classes
• Often the Class is too generalized to be
modified
• Behavior is partially left unspecified

Abstract Methods and Classes
Abstract method: a method without a BODY
– Only declared, but not defined
Abstract class: a class with one or more
abstract methods
• It is not permitted to make instances of
abstract classes
– Intended to be defined by the subclasses

Example
 
• Abstract class C1 with abstract
methods A and B
• Abstract class C2. Defines
method A but not method B.
Adds data elements d3 and d4
• Concrete class C3. Defines
method B. Adds the methods D
and E and the data element d5. 

abstract class ClassName {
// <class_body>;
}
• Classes without abstract methods can be
declared abstract
• A subclass to a concrete superclass can be
abstract
• Constructors can be defined on abstract classes.

abstract class A {
abstract void X();
abstract void Y();
void Z() {
System.out.println("This is in A");
}
}
class B extends A{
void Y(){
System.out.println("This is in B");
}
}
class C extends B{
void X(){
System.out.println("This is in C");
}
void next(){
System.out.println("This is something else");
}
}

abstract class A {
abstract void X();
abstract void Y();
void Z() {
System.out.println("This is in A");
}
}
abstract class B extends A{ // X() is not defined
void Y(){
System.out.println("This is in B");
}
}
class C extends B{
void X(){
System.out.println("This is in C");
}
void next(){
System.out.println("This is something else");
}
}

public class Driver {
public static void main(String[] args) {
C val = new C();
// B val = new C();
val.Z();
val.Y();
val.X();
val.next();
}
}

public class Driver {
public static void main(String[] args) {
// C val = new C();
B val = new C();
val.Z();
val.Y();
val.X();
val.next();
}
}

Multiple Inheritance
• Employee and
Student
– Both can be TAs
– Both are Persons
• Hence class
TeachingA needs
properties from both
the classes
• Name Clash Problem
– Which department???
• Combination problem
– Can we combine
department from both the
classes?
• Selection problem
– Can we select between the
two departments?
• Replication problem
– Should there be two
Ta = new TeachingA(); departments?
Ta.department; 

Interface 
• An interface is a collection of method
declarations
– class-like concept
• Describes a set of methods that a class can be
forced to implement
• methods and attributes are implicitly public
Attributes are implicitly static and final
Methods are implicitly abstract (no body)
• Cannot be instantiated
• Can be used to define references

Rule (1)
• An interface can extend another interface,
Cannot extend a class
• can extend multiple interfaces
interface Car extends Comparable {
void print();
} // Wrong
interface Car extends Orderable, Comparable{
// ...

Rule (2)
• A class can extend only one class
• A class can implement multiple interfaces
class Person extends Employee
implements Orderable, Comparable {
// …

interface InterfaceName {
// "constant" declarations
// method declarations
}
class ClassName implements InterfaceName {
// ...
}
class ClassName extends SuperClass implements InterfaceName {
// ...
}
class ClassName extends SuperClass implements
InterfaceName1,InterfaceName2 {
// ...
}
interface InterfaceName2 extends InterfaceName {
// ...
}

Example
public interface Comparable {
boolean isEqual(String s);
}
public class Car implements Comparable {
private String licencePlate;
public boolean isEqual(String s){
return licencePlate.equals(s);
}
}
public class Employee implements Comparable{
private String name;
public boolean isEqual(String s){
return name.equals(s);
}

Example (2)
public class Foo {
private Comparable objects[];
public Foo(){
objects = new Comparable[3];
objects[0] = new Employee();
objects[1] = new Car();
objects[2] = new Employee();
}
public Comparable find(String s) {
for(int i=0; i< objects.length; i++)
if(objects[i].isEqual(s))
return objects[i];
}
}

The Iterator Interface
• The Iterator interface in java.util is a basic
iterator that works on collections
package java.util;
public interface Iterator <E>{
boolean hasNext();
E next();
void remove();
}

Iterator iter = myShapes.iterator();
while (iter.hasNext()) {
Shape s = (Shape)iter.next();
s.draw();
}

• The cast (Shape) is important as next()
returns Object

The Cloneable Interface
• A class X that implements the Cloneable
interface tells clients if the objects can be
cloned
• Empty interface
• Prevention of cloning
– Necessary if unique attribute, e.g., database lock
or open file reference
– Object.clone() should throw an exception:
CloneNotSupportedException

Examplepublic class Employer extends Person implements Cloneable {
public Object clone(){
try {
return (super.clone()); // protected in Object
}
catch (CloneNotSupportedException e){
return null;
}
// …
}



Inner Class
• Fundamental language feature, added in Java
1.1
• Used a lot in Swing (GUI programming)
• Nest a class within a class
• Class name is hidden 

class Airplane {
String code = "11";
Blackbox box = new Blackbox();
public void prt(){
int [] location = {1,2,3,4,5,6};
for(int i:location)
System.out.println(i);
}
public class Blackbox {
String code = "22";
public void print() {
System.out.println(code);
// how to print “code” from Airplane ???
}
}

class Airplane {
String code = "11";
Blackbox box = new Blackbox();
public void prt(){
int [] location = {1,2,3,4,5,6};
for(int i:location)
System.out.println(i);
}
public class Blackbox {
String code = "22";
public void print() {
System.out.println(code);
System.out.println(Airplane.this.code);
}
}

public class OuterTest {
public static void main(String [] args){
Airplane box1 = new Airplane();
box1.box.print();
box1.prt();
}
}

public class OuterTest {
public static void main(String [] args){
Airplane box1 = new Airplane();
Airplane.Blackbox box2 = box1.new Blackbox();
box1.box.print();
box1.prt();
box2.print();
}
}

class Airplane {
String code = "11";
Blackbox box = new Blackbox();
public void prt(){
int [] location = {1,2,3,4,5,6};
for(int i:location)
System.out.println(i);
}
private class Blackbox {
String code = "22";
public void print() {
System.out.println(code);
System.out.println(Airplane.this.code);
}
}

public class OuterTest {
public static void main(String [] args){
Airplane box1 = new Airplane();
Airplane.Blackbox box2 = box1.new Blackbox(); //Won`t Work
box1.box.print();
box1.prt();
box2.print();
}

• Each inner class can independently inherit
from other classes
– The inner class is not limited by whether the
outer class is already inheriting from a class
• With concrete or abstract classes, inner
classes are the only way to produce the effect
of
– "multiple implementation inheritance"
 

Types of Inner ClassesNested Class
– Inner static class
Member Class
– Similar to Nested class
– BUT, not static
Local Class
– Scope is limited to a method
– Used for small helper classes 

Package 
• Classes are abstraction of real world objects
• Choosing correct name can lead to ambiguity
– Class named “Cloud” have several meanings
A purpose of Package: provide contextual
namespace

– Class named “Cloud” in “Computing” package has
more precise meaning

• Same way we organize files inside directories
• Organize according to
– Functionalities
– Usability
– Category
Package names are separated by periods (.)
– E.g. Java.aaa.bbb. …
• Can contain Classes or Packages
• Qualified name of a class include its package
name
– Computing.Cloud :: Class “Cloud” is within the
package named “Computing”
• The designers of Java proposed an
Internet-wide unique package naming
scheme
• Includes the Internet domain name of the
organization within which the package was
developed
• The domain is reversed and the
subdomains become packages
computaholics.in -> in.computaholics
The domain portion is prepended to any
packages developed within
computaholics.in 
Computing.Cloud -> in.computaholics.Computing.Cloud
• Guarantees that no other organization will
create a class whose name conflicts with
this 
• Proposed naming scheme create long names
– Difficult to handle
– Reduces code readability
– Computing.Cloud -> in.abc.Computing.Cloud
• To avoid having to use the fully qualified class
names for all the classes
– We can import ONE or ALL the classes in a given
package

// Import a single class
import in.abc.Computing.Cloud;
// Import all classes from the specified packages
import in.acb.Computing.*;
import java.io.*;
import java.net.*;

Java Foundation Packages
• java.lang
– Contains classes for primitive types, strings, math
functions, threads, and exception
• java.util
– Contains classes such as vectors, hash tables, date etc.
• java.io
– Stream classes for I/O
• java.awt
– Classes for implementing GUI – windows, buttons, menus
etc.
• java.net
– Classes for networking
• java.applet
– Classes for creating and implementing applets
• Import ONLY imports public classes from the
specified package
– Classes which are not public cannot be referenced
from outside their package.
• There is no way to "import some of the classes“
• Import statements must appear at the top of the
file after the package statement and before any
class or interface definitions.

Creating Your Own Package
1.Declare the package at the beginning of a file using the form
package packagename;
2. Define the class that is to be put in the package and declare
it public.
3. Create a subdirectory <packagename> under the directory
where the main source files are stored.
4. Store the listing as classname.java in the subdirectory
created.
5. Compile the file. This creates .class file in the subdirectory.

Steps for creating Packages
• Use keyword package at the beginning of the
file
• Create a directory of that package name
• Compile the file and keep the .class files in this
directory
• Set the classpath from the root up to the
directory created above
• Use the import keyword to import 

package p1;
public class ClassA
{
public void displayA( )
{
System.out.println(“Class A”);
}
}
Source file: ClassA.java
Subdirectory: p1
ClassA.class: p1

import p1.*;
Class testclass
{
public static void main(String str[])
{
ClassA obA=new ClassA();
obA.displayA();
}
}
Source file: testclass.java
testclass.java and testclass.class-> in a
directory of which p1 is subdirectory

How compiler locates Classes
1. Check current directory
2. Compiler looks through all directories specified
in the classpath for
– The class file
OR
– The sub-directory that has the name of the imported
package
3. looks for the file in one of the imported
packages
4. Finally looks for file in java.lang package
5. Else, gives an error

CLASSPATH
• Uses of classes, such as, String, Integer and
other primitive types are regular.
• Do we have to import java.lang.* each time?
– Why not?
• The path to this package is already included by
an EV
– CLASSPATH
• If you store a class named TestClass in a package
named testpack, you should access that class as
testpack.TestClass
Or, change CLASSPATH variable.
• If you don’t specify package name,
– current working directory [.] is taken by default in the
CLASSPATH variable defined by JRE
• If you are working on your source code in a
directory named C:\myjava then set your
CLASSPATH to:
set CLASSPATH= “. ; C:\myjava ; C:\<java\classes>”

• If you use * notation for import, rather than
importing specific classes that are required,
will that affect compile-time and run-time
performance of the program ?

ArrayList
boolean add(E e)

-Appends the specified element to the end of this list.

void add(int index, E element)
-Inserts the specified element at the specified position in this list.

Objcect remove(int index)
-Removes the element at the specified position in this  list.


boolean remove(Object o)
-Removes the first occurrence of the specified element from this list, if it is present.

boolean contains(Object o)
-Returns true if this list contains the specified element.

Object get(int index)
-Returns the element at the specified position in this list.

int indexOf(Object o)
 -Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not
contain the element.

boolean isEmpty()
Returns true if this list contains no elements.
Powered by Blogger.