Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
29 views

Java Inheritancepolymorphism BW

1. Inheritance allows a subclass to inherit properties from a superclass, including data fields and methods. A subclass extends a superclass and inherits its public and protected fields and methods. 2. Polymorphism allows subclasses to override or extend the behavior of methods defined in the superclass. Subclasses can define their own implementation of a method while reusing the method name. 3. Constructors are not inherited in subclasses. When a subclass object is instantiated, the superclass constructor is implicitly or explicitly called using the super keyword before the subclass constructor executes. This ensures superclass fields are initialized before subclass fields.

Uploaded by

weetan studio
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Java Inheritancepolymorphism BW

1. Inheritance allows a subclass to inherit properties from a superclass, including data fields and methods. A subclass extends a superclass and inherits its public and protected fields and methods. 2. Polymorphism allows subclasses to override or extend the behavior of methods defined in the superclass. Subclasses can define their own implementation of a method while reusing the method name. 3. Constructors are not inherited in subclasses. When a subclass object is instantiated, the superclass constructor is implicitly or explicitly called using the super keyword before the subclass constructor executes. This ensures superclass fields are initialized before subclass fields.

Uploaded by

weetan studio
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Inheritance &

Polymorphism
13 March 2019
Contents
• Inheritance
• Polymorphism
Inheritance

https://www.pinterest.com/pin/16888567332662930/
Inheritance (“is-a relationship”)
• A way of grouping a more
general variables and
methods into a super
class; a specialized subset
(sub-class) extends /
inherits from) this super
class.
• Inheritance refers to
objects inheriting
properties (data & https://docs.oracle.com/javase/tutorial/java/concepts/inheritance.html

methods) of another class.


http://java5tutor.info/java/ooconcepts/inheritance.html
General syntax:
subclassname extends superclassname
For example:
public class C1 extends C2
{ . . . }
Superclass Subclass

C2 C1
public class Circle /** Return radius */
{ public double getRadius()
/** The radius of the circle */ { return radius; }
private double radius;
/** Set a new radius */
/** Construct a circle with radius 1 public void setRadius(double
*/ newRadius)
public Circle() { radius = (newRadius >= 0) ?
{ radius = 1.0; } newRadius : 0; }

/** Construct a circle with a /** Return the area of this circle */
specified radius */ public double findArea()
public Circle(double newRadius) { return radius* radius *3.14159; }
{ radius = newRadius; } Circle }
-radius
+getRadius
+setRadius
+findArea
// Cylinder.java: Class definition for describing Cylinder
public class Cylinder extends Circle
{ private double length = 1;

public double getLength() /** Return length */


{ return length; }

public void setLength(double length) /** Set length */


{ this.length = length; }

/** Return the volume of this cylinder */


public double findVolume()
{ return findArea() * length; }

}
Superclass Subclass
supertype subtype
Circle Cylinder
-radius
-length
+getRadius
+setRadius +getLength
+findArea +setLength
+findVolume
Cylinder cylinder = new Cylinder();
System.out.println("The length is " + cylinder.getLength());
System.out.println("The radius is " + cylinder.getRadius());
System.out.println("The volume of the cylinder is " +
cylinder.findVolume());
System.out.println("The area of the circle is " +
cylinder.findArea());

The output is
The length is 1.0
The radius is 1.0
The volume of the cylinder is 3.14159
The area of the circle is 3.14159
Superclass Subclass
supertype subtype

Circle Cylinder
-radius
-length
+getRadius
+setRadius +getLength
+findArea +setLength
+findVolume

• A subclass inherits all public and default data and methods


from its superclass.
• Private data and methods belong to superclass are not
inherited by its subclass.
• Example:
• Data radius in Circle is private data, so it is not inherited
by Cylinder.
• All public methods in Circle are inherited by the Cylinder
class.
Superclass and Subclass Constructor
• A constructor is used to construct an instance of a class.
• When an object of subclass is instantiated, the
superclass’s constructor must be first called to initialise
the superclass members of the subclass’s object.
• If the subclass’s constructor is omitted, the subclass’s
default constructor calls the superclass’s default or no-
arg constructor.
• Unlike data and methods, a superclass's constructors
are not inherited in the subclass. They can only be
invoked from the subclasses' constructors, using the
keyword super.
• If the keyword super is not explicitly used, the
superclass's no-arg constructor is automatically invoked.
Using the Keyword super
The keyword super refers to the superclass of the
class in which super appears. This keyword can
be used :
• To call a superclass constructor.
• To call a superclass method.

• You must use the keyword super to call the


superclass constructor.
• Java requires that the statement that uses the
keyword super appear first in the constructor.
• Invoking a superclass constructor’s name in a
subclass causes a syntax error.
Superclass’s Constructor Is Always Invoked
A constructor may invoke an overloaded constructor
or its superclass’s constructor. If none of them is
invoked explicitly, the compiler puts super() as the
first statement in the constructor. For example,

public Cylinder() { public Cylinder() {


is equivalent to
} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}

17
Constructing an instance of a class
Constructor Chaining invokes all the superclasses’
Example 1 constructors along the inheritance
chain.
class Person
{ public Person()
{ CVCCno-arg constructor is invoked");}
System.out.println("Person's
}

class Employee extends Person


{ public Employee()
{ this("Invoke Employee’s overloaded constructor");
System.out.println("Employee's no-arg constructor
is invoked");
}

public Employee(String s)
{ System.out.println(s); }
}

public class Faculty extends Employee


{ public static void main(String[] args)
{ new Faculty(); }

public Faculty()
{ System.out.println("Faculty's no-arg constructor is invoked"); }
Example 2

public class Circle


{ private double radius;
public Circle()
{ System.out.println(“No-arg Circle's constructor." );
radius = 1.0; }
}

public class Cylinder extends Circle


{ private double length = 1;
public Cylinder()
{ System.out.println(“No-arg Cylinder's constructor." ); }
}

public class TestCylinder


{ public static void main(String[] args)
{ Cylinder cylinder1 = new Cylinder();}
Example 3
public class Circle
{ private double radius;
public Circle()
{ System.out.println(“No-arg Circle's constructor." );
radius = 1.0; }
public Circle(double newRadius)
{ System.out.println(“Overloading Circle's constructor." );
radius = newRadius; }
}

public class Cylinder extends Circle


{ private double length = 1;
public Cylinder()
{ System.out.println(“No-arg Cylinder's constructor." ); }
public Cylinder(double radius, double leng)
{ super(radius);
System.out.println(“Overloading Cylinder's constructor." );
length = leng; }
}
public class TestCylinder
{ public static void main(String[] args)
{ Cylinder cylinder1 = new Cylinder();
Cylinder cylinder2 = new Cylinder(5, 10);
}
}
Superclass without no-arg Constructor

class Fruit
{
ERROR
public Fruit(String name)
{
System.out.println("Fruit's constructor is invoked");
}
} It is better to provide a
no-arg constructor to
public class Apple extends Fruit avoid programming
{ } errors.
Calling Superclass Methods
The keyword super can also be used to reference a
method other than constructor in the superclass.
General syntax:
super.method(parameters)
For example, in class Cylinder:
public double findVolume()
{ return super.findArea() * length; }
The final Modifier
• The modifiers are used on classes and class members
(data and methods), except that the final modifier can also
be used on local variables in a method.
• A final local variable is a constant inside a method.
The final class cannot be extended:
final class Math
{ ... }

The final variable is a constant:


final static double PI = 3.14159;

• The final method cannot be overridden by its


subclasses.
The protected Modifier
• The protected modifier can be applied on data
and methods in a class. A protected data or a
protected method in a public class can be accessed
by any class in the same package or its subclasses,
even if the subclasses are in a different package.
• private, default, protected, public

visibility increases
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }

package p2;

public class C3 public class C4 public class C5 {


extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }
Polymorphism
• Overloading is a form of polymorphism which to
provide more than one method with the same
name but with different signatures to distinguish
them.
• Overriding is also a form of polymorphism which
means that a subclass class defines a method that
the same signature and return type as in its
superclass but the implementation of both
methods are different.
Overloading

https://javahungry.blogspot.com/2018/11/method-
overloading-in-java-with-examples.html

https://www.programcreek.com/2009/02/overriding-and-
overloading-in-java-with-examples/

https://programmingstack.com/java-
methods/9-java/49-java-method-
overloading.html
Overriding
Overriding Methods in the Superclass
// New cylinder class that overrides the findArea()
// Method defined in the circle class.

public class Cylinder extends Circle


{ /** Return the surface area of cylinder. The formula is
* 2 * circle area + cylinder body area */

public double findArea()


{
return 2 * super.findArea() +

2 * getRadius() * Math.PI * length;


}
// Other methods are omitted
}
Overriding Methods in the Superclass
• An instance method can be overridden only if it is
accessible. Thus a private method cannot be overridden,
because it is not accessible outside its own class.
• If a method defined in a subclass is private in its
superclass, the two methods are completely unrelated.
• Like an instance method, a static method can be
inherited. However, a static method cannot be
overridden.
• If a static method defined in the superclass is redefined
in a subclass, the method defined in the superclass is
hidden.
class VideoTape
{ String title; // name of the item Review Questions
int length; // number of minutes
boolean avail; // is the tape in the store?
public VideoTape( String ttl, int lngth )
{ title = ttl; length = lngth; avail = true; }
public void show()
{ System.out.println( title + ", " + length + " min. available:" + avail ); }
}

class Movie extends VideoTape


{ String director; // name of the director
String rating; // G, PG or X
public Movie( String ttl, int lngth, String dir, String rtng )
{ super( ttl, lngth ); // use the super class' constructor
director = dir; // initialize what's new to Movie
rating = rtng; }
public void show()
{ super.show(); //invoke superclass show() method
System.out.println( "dir: " + director + " Rating : " + rating ); }
}
class TapeStore
{ public static void main ( String args[] )
{ VideoTape item1 = new VideoTape("War Of the Worlds", 90 );
Movie item2 = new Movie("Jaws", 120, "Spielberg", "PG" );
item1.show();
item2.show();
}
}

Output:
Resources
• BlueJ http://bluej.org/
• Think Java (Allen Downey & Chris Mayfield)
– http://greenteapress.com/thinkjava6/thinkjava.pdf
• Online Java Compiler
– https://www.tutorialspoint.com/compile_java_online.php
– https://www.jdoodle.com/online-java-compiler
– https://www.compilejava.net
• Online Java Tutorial
– https://docs.oracle.com/javase/tutorial/java/
– https://www.w3schools.in/java-tutorial/
– https://www.tutorialspoint.com/java/

You might also like