class base { : } class derived extends base { : }
class Common { double Pi = 3.14; double getSquare(double R) { return(R*R); } } class Circle extends Common { void area(double R) { double ar = Pi * getSquare(R); System.out.println(“area = ” + ar); } } class Cylinder extends Common { void volume (double r, double h ) { double vol = Pi * getSquare(r) * h; System.out.println(“Volume of Cylinder = “ + vol); } } class IDemo { public static void main(String args[]) { Circle c = new Circle(); c.area(10.5); Cylinder cyl = new Cylinder(); cyl.volume(12.5, 7.8); } }Explanation In this program, the method getSquare() is the member of class Common, which is used in Circle class for calculating area of circle (line 13) and in Cylinder class for calculating the volume of cylinder (line 21).
In Java, inheritance can be of 4 types:
Overriding in Subclass | Validity | Why |
---|---|---|
public int job (int i, fl oat f, String s) | Valid | Same Signature |
protected int job (int i, fl oat f, String s) | Invalid | Less accessibility |
public fl oat job (int i, fl oat f, String s) | Invalid | Diff erent Return type |
public int job (int i, fl oat f) | Invalid | less parameters |
public int job (fl oat f, int i, String s) | Invalid | Parameter types are in diff erent order |
public int job (int x, fl oat f, String t) | Valid | Same signature |
class B { void readFile()throws FileNotFoundException { // Overridden method ------------ ----------- } } class D extends B { void readFile() throws FileNotFoundException { // Overriding method ------------- ------------- } }The above syntax is error free but if you remove throws
class B { void readFile()throws FileNotFoundException { // Overridden method ------------- } } class D extends B { void readFile() { // Overridden method -------------- } }The above syntax is error free, even though throws clause is not used while overriding the method.