Você está na página 1de 68

UNIT - 3

Inheritance
Method Overriding
Constructor Calling
Runtime Polymorphism
Usage of Final
Package
Interfaces
Inheritance
• Allows the creation of hierarchical classification
• To inherit a class , we use the extends keyword
• Can specify only one superclass for any
subclass that you create
• Does not support inheritance of multiple
superclass
• A class member that has been declared as
private will remain private to its class. It is not
accessible by any code outside its class,
including subclasses.
Example on Inheritance
• A company needs information about their
employees like their names, ages and salaries
– class employee is created.
• the company have also programmers and
database specialists – need to add
programming language and database tool
public class Employee { public class Employee {
String name;
int age;
String name; double salary;
int age; public void printData(){
double salary; System.out.println("name: " + name);
System.out.println("age: " + age);
String language;
System.out.println("salary: " + salary);
String databaseTool; } }
….
…. public class Programmer extends Employee {
String language;
public void printData(){
} super.printData();
System.out.println("language: " + language);
} }

public class DatabasePro extends Employee {


String databaseTool;
public void printData(){
super.printData();
System.out.println("Database Tool: " + databaseTool);
}
}
3
Another Example – Animal Simulation
These are all Animals so
will make Animal –
Super Class
Instance Variables -
Picture , Food , Hunger,
Location
Methods – makenoise() ,
eat() , Sleep(), roam()
Wolf Class Methods
Method overriding - Definition
• Whenever same method name is existing in
both base class and derived class with same
types of parameters or same order of
parameters is known as method Overriding
• Advantage:
– Method Overriding is used to provide specific
implementation of a method that is already
provided by its super class.
– Method Overriding is used for Runtime
Polymorphism
Rules
• method must have same name as in the
parent class.
• method must have same parameter as in the
parent class.
• must be IS-A relationship (inheritance)

• Example : Overidedemo.java
IS-A Relationship
• Inheritance tree – follows is-a relationship
• Ex : Triangle is a Shape
• Cat is-a Feline
Difference between Overloading and Overriding
Overloading Overriding
1 Whenever same method or Constructor is existing Whenever same method name is
multiple times within a class either with different existing multiple time in both base
number of parameter or with different type of and derived class with same
parameter or with different order of parameter is number of parameter or same
known as Overloading. type of parameter or same order
of parameters is known as
Overriding.
2 Arguments of method must be different at least Argument of method must be
arguments. same including order.
3 Method signature must be different. Method signature must be same.
4 Private, static and final methods can be overloaded. Private, static and final methods
can not be override.
5 Also known as compile time polymorphism or static Also known as run time
polymorphism or early binding. polymorphism or dynamic
polymorphism or late binding.
6 Overloading can be exhibited both are method and Overriding can be exhibited only
constructor level. at method label.
7 The scope of overloading is within the class. The scope of Overriding is base
class and derived class.
8 Overloading can be done at both static and non-static Overriding can be done only at
methods. non-static method.
9 For overloading methods return type may or may not For overriding method return type
be same. should be same.
Using super to call base class constructor
• class BoxWeight extends Box {
• double weight; // weight of box
• // initialize width, height, and depth using super()
• BoxWeight(double w, double h, double d, double
m) {
• super(w, h, d); // call superclass constructor
• weight = m;
• }
• }
• class MySuper {
• int a = 1;

• MySuper() {
• System.out.print("-a" + a);
• } }

• class MySub extends MySuper {

• MySub(int c) {
• System.out.print("-c" + c); - a1 –c2
• } } The subclass’s
• constructor
• class TestInheritance { implicitly calls
• public static void main(String[] args){ superclass’s
• MySub mySub = new MySub(2); no-argument
• } } constructor
Constructors Call
• When a class hierarchy is created, in what order
are the constructors for the classes that
make up the hierarchy executed ?

• In a class hierarchy, constructors complete their


execution in order of derivation, from superclass
to subclass.

• Even if super() is not given it calls the


parameterless constructor of parent class
• Example : classcallingone.java
Animal an;
an = myDog;
an.roam();
Dynamic method Dispatch
• Method overriding forms the basis for one of Java’s
most powerful concepts: dynamic method dispatch.
• Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time,
rather than compile time.
• Dynamic method dispatch is important because this is
how Java implements run-time polymorphism.

• Run-time polymorphism is one of the most powerful


mechanisms that object oriented design brings to bear
on code reuse and robustness
• Example : FindArea.java
// Using run-time polymorphism. // override area for right triangle
class Figure { double area() {
double dim1; System.out.println("Inside Area for Triangle.");
double dim2;
Figure(double a, double b) { return dim1 * dim2 / 2;
dim1 = a; }
dim2 = b; }
}
double area() { class FindArea {
System.out.println("Area for Figure is undefined.");
return 0; public static void main(String args[]) {
} Figure f = new Figure(10, 10);
} Rectangle r = new Rectangle(9, 5);
class Rectangle extends Figure { Triangle t = new Triangle(10, 8);
Rectangle(double a, double b) { Figure figref;
super(a, b);
} //f.area();
// override area for rectangle figref = r;
double area() { System.out.println("Area is " + figref.area());
System.out.println("Inside Area for Rectangle."); figref = t;
return dim1 * dim2; System.out.println("Area is " + figref.area());
}
} figref = f;
class Triangle extends Figure { System.out.println("Area is " + figref.area());
Triangle(double a, double b) { }
super(a, b);
} }
Super class can Refer a subclass object
class RefDemo {
Public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " +
weightbox.weight);

// assign BoxWeight reference to Box reference


plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);

/* The following statement is invalid because plainbox


does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);

}
• What happens when the following program is compiled and run?
public class MySuper {
int b = 1;
}

class MySub extends MySuper {


int c = 5;
MySub(int c) {
System.out.print("-c" + this.c); }
void myMethod(){
System.out.print("-b" + b); } }

class TestMyProgram {
public static void main(String[] args){ -C5 –b1
MySub mySub = new MySub(4);
mySub.myMethod(); } } Without this
-c4-b1
Some Classes
Should not
be instantiated
Abstract Class
• an abstract class cannot be directly instantiated
with the new operator.
• They are mainly used as super classes.
• It has one or more abstract methods.
• An abstract method is a method without a body,
which are not defined.
• Abstract methods can be overridden by
subclasses by specifying the abstract type
modifier.
Usage
• It is possible to instantiate a sub class that
extends an abstract class.
• It is not mandatory to have any abstract
methods inside an abstract class.
• It is allowed in Java to declare a subclass of an
abstract class also abstract
• Example :constructor.AbstractAreas.java
Using final with Inheritance
• The keyword final has three uses.
– Constant
– To Prevent Method overriding
– To Prevent Inheritance
Prevent Overriding
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Prevent Inheritance
• final class A {
• //...
• }
• // The following class is illegal.
• class B extends A { // ERROR! Can't subclass A
• //...
• }
Multilevel Inheritance
• Single base class + single derived class +
multiple intermediate base classes
class Faculty {
float total_sal=0,
salary=30000; }

class HRA extends Faculty { float hra=3000; }


class DA extends HRA { float da=2000; }

class Science extends DA {


float bonous=2000;
public static void main(String args[]) {
Science obj=new Science();
obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonous;

System.out.println("Total Salary is:"+obj.total_sal); } }


Package
• Packages are containers for classes. They are
used to keep the class name space
compartmentalized.
• package pkg;
• the .class files for any classes you declare to
be part of MyPackage must be stored in a
directory called MyPackage.
package MyPack;
class Balance {
String name; class AccountBalance {
double bal; public static void main(String args[])
Balance(String n, double b) { {
name = n; Balance current[] = new Balance[3];
bal = b; current[0] = new Balance
} ("K. J. Fielding", 123.23);
void show() { current[1] = new Balance
if(bal<0) ("Will Tell", 157.02);
System.out.print("--> "); current[2] = new Balance
System.out.println(name + ": $" + ("Tom Jackson", -12.33);
bal);
} for(int i=0; i<3; i++) current[i].show()
} }
}
• Name - AccountBalance.java and put it in a
directory called MyPack.
• Compile and Generate the Class file
• While executing move to one directory up of
MyPack then give
java MyPack.AccountBalanace
• It means AccountBalance is now part of
MyPack - Package
CLASSPATH
• Inorder for a program to find MyPack one of
the following two things must be true.
– Either the program is executed from a directory
immediately above MyPack (easy)
– Or, CLASSPATH must be set to include the path to
MyPack (finds MyPack whatever directory the
program is in)
Access Protection
• Classes and packages are both means of
encapsulating and containing the name space
and scope of variables and methods

• Java addresses four categories of visibility for


class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor
subclasses
• The three access modifiers, private, public, and
protected, provide a variety of ways to
produce the many levels of access required by these
categories.
Private No Modifier Protected Public

Same class Yes Yes Yes Yes

Same package No Yes Yes Yes


subclass
Same package No Yes Yes Yes
non-subclass
Different No No Yes Yes
package
subclass
Different No No No Yes
package non-
subclass
Access Protection Example
package p1;
p1/Protection.java
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;

public Protection() {
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
Access Protection Example
package p1;
p1/Derived.java

class Derived extends Protection {


Derived() {
System.out.println("derived constructor");
System.out.println("n = " + n);
// class only
// System.out.println("n_pri = "4 + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
Access Protection Example
package p1;
p1/SamePackage.java
class SamePackage {
SamePackage() {
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
Access Protection Example
p1/Demo.java
// Demo package p1.
package p1;
// Instantiate the various classes in p1.
public class Demo {
public static void main(String args[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}
Access Protection Example
Command Prompt
C:\Users\Hai...!\Desktop\JAVA>javac p1\Protection.java

C:\Users\Hai...!\Desktop\JAVA>javac p1\Derived.java

C:\Users\Hai...!\Desktop\JAVA>javac p1\SamePackage.java

C:\Users\Hai...!\Desktop\JAVA>javac p1\Demo.java

C:\Users\Hai...!\Desktop\JAVA>java p1.Demo
Access Protection Example
base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
derived constructor
n=1
n_pro = 3
n_pub = 4
base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
same package constructor
n=1
n_pro = 3
n_pub = 4
Access Protection Example
p2/Protection2.java
package p2;
class Protection2 extends p1.Protection {
Protection2() {
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
Access Protection Example
package p2;
p2/OtherPackage.java
class OtherPackage {
OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
Access Protection Example
p2/Demo.java
// Demo package p2.
package p2;
// Instantiate the various classes in p2.
public class Demo {
public static void main(String args[]) {
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
Access Protection Example
C:\Users\Hai...!\Desktop\JAVA>javac p2\Protection2.java

C:\Users\Hai...!\Desktop\JAVA>javac p2\OtherPackage.java

C:\Users\Hai...!\Desktop\JAVA>javac p2\Demo.java

C:\Users\Hai...!\Desktop\JAVA>java p2.Demo
Access Protection Example
base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
n_pro = 3
n_pub = 4
base constructor
n=1
n_pri = 2
n_pro = 3
n_pub = 4
other package constructor
n_pub = 4
Importing Packages
package MyPack;
/* Now, the Balance class, its constructor, and its
show() method are public. This means that they can
be used by non-subclass code outside their package.
*/
public class Balance {
String name;
double bal;

public Balance(String n, double b) {


name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
• import MyPack.*;
• class TestBalance {
• public static void main(String args[]) {
• /* Because Balance is public, you may use
Balance class and call its constructor. */
• Balance test = new Balance("J. J. Jaspers",
99.88);
• test.show(); // you may also call show()
• }
• }
Interfaces
• Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
• An interface is defined much like a class. This is a
simplified general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value; }
• An interface can contain any number of methods
which are all abstract.
• An interface is written in a file with
a .java extension, with the name of the interface
matching the name of the file.
• The byte code of an interface appears in
a .class file.
• Reasons on using interface
– To achieve abstraction
– To support the functionality of multiple inheritance
– To achieve loose coupling
Main Hint about Interfaces
Interface functions should be public and abstract.
Interface fields should be public and final.
Use the Keyword interface to define an interface.
If you define a public interface with
name myInterface the java file should be named
as myInterface.java.
A class implementing an interface should use the
keyword implements.
• No objects can be created from an interface.
• Interfaces don't have constructors as they
can't be initiated
• An Interface can extends one or more
interfaces.
• You can define a reference of type interface
but you should assign to it an object instance
of class type which implements that interface
Diff between Interface & Class
• 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.
• An interface is a reference type in Java.
• It is similar to class. It is a collection of abstract
methods.
• A class implements an interface, thereby
inheriting the abstract methods of the interface.
• No Access modifier – default access , Available to
other members of the package in which its
declared
• Public – can be used in any other code
Callback.java
interface Callback {
void callback(int param);
}
Implementing Interfaces
• Only the function definition exists, implementation of the
function is done in the class in which its used
class classname implements interface1,interface 2
{
….
}

Ex: class Client implements callback


{
public void callback(int p)
{ System.out.println(“callback function”);
}
}
public interface Shape {
//implicitly public, static and final
public String LABEL="Shape";

//interface methods are implicitly abstract


public void draw();
double getArea();
}

Shape.java
Public class Circle implements Shape
{
private double radius;
public Circle(double r){ this.radius = r; }
@Override
public void draw()
{ System.out.println("Drawing Circle"); }

@Override
public double getArea()
{ return Math.PI*this.radius*this.radius; }

public double getRadius()


{ return this.radius; }
}
public class ShapeTestClass {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Circle c = new Circle(5);
double da = c.getArea();

System.out.println("Area" + da);

//upcasting - define a reference of type shape and assign to circle object

Shape sh = new Circle(10);


// calls the get Area in circle class
System.out.println(sh.getArea());

}
• interface Bank{
• float rateOfInterest();
• }
B reference variable
• class SBI implements Bank{ points to SBI class and
• public float rateOfInterest(){return 9.15f;} so the output would be
9.15 f
• }
• class PNB implements Bank{
• public float rateOfInterest(){return 9.7f;}
• }
• class TestInterface2{
• public static void main(String[] args){
• Bank b=new SBI();
• System.out.println("ROI: "+b.rateOfInterest());
• }}
Extended Interfaces
One interface can inherit another by use of the public void meth2() {
keyword extends System.out.println("Implement meth2().");
// One interface can extend another. }
interface A {
void meth1(); public void meth3() {
System.out.println("Implement meth3().");
void meth2();
}
} }
// B now includes meth1() and meth2() -- it class IFExtend {
adds meth3(). public static void main(String arg[]) {
interface B extends A { MyClass ob = new MyClass();
void meth3();
ob.meth1();
}
ob.meth2();
// This class must implement all of A and B ob.meth3();
class MyClass implements B { }
public void meth1() { }
System.out.println("Implement meth1().");
All methods of interface A and B have to be
}
implemented
Wrapper Classes

• A wrapper class wraps (encloses) around a data


type and gives it an object appearance.
Wherever, the data type is required as an
object, this object can be used.
• abstract methods that return the value of the
object in each of the different number
formats.
• doubleValue( ) returns the value as a double,
floatValue( ) returns the value as a float
compareTo()Compares this Number object to the
1
argument.
equals()Determines whether this number object is equal
2
to the argument.
valueOf()Returns an Integer object holding the value of
3
the specified primitive.
toString()Returns a String object representing the value of
4
a specified int or Integer.
parseInt()This method is used to get the primitive data
5
type of a certain String.
6 abs()Returns the absolute value of the argument.
ceil()Returns the smallest integer that is greater than or
7 equal to the argument. Returned as a double.

floor()Returns the largest integer that is less than or equal


8
to the argument. Returned as a double.
rint()Returns the integer that is closest in value to the
9
argument. Returned as a double.
round()Returns the closest long or int, as indicated by the
10
method's return type to the argument.
11 min()Returns the smaller of the two arguments.
12 max()Returns the larger of the two arguments.

Você também pode gostar