7 Inheritence (Static Dynamic Binding)
7 Inheritence (Static Dynamic Binding)
Output:
print in superclass.
print in superclass.
Since the print() method of superclass is static, compiler knows that it will not be
overridden in subclasses
compiler knows during compile time which print() method to call and hence no
ambiguity
Output: object.
print in superclass.
print in subclass.
24/10/2023 Interface - multiple inheritance Page 6
Remarks
Cannot override static methods in java
In a static context, cannot access a non-static variable
i.e., in a static method, can access only to static variables because non-
static variables depend on the existence of an instance of a class.
Same for static class (nested static class)
There are some related classes that need to share some lines of
code, so these lines of codes can be put within abstract class
class Main {
public static void main(String args[]) {
DerivedClass d = new DerivedClass(3);
Output:
} Output???
} MyBaseClass Constructor called
DerivedClass Constructor called
Shape(String name) {
this.objectName = name;
}
// constructor
Rectangle(int length, int width, String name) {
super(name);
this.length = length;
this.width = width;
}
@Override
public void draw() {
System.out.println("Rectangle has been drawn ");
}
@Override
public double area() {
return (double)(length*width);
}
}
24/10/2023 Inheritance Page 13
Example…
class Circle extends Shape {
double pi = 3.14; int radius;
//constructor
Circle(int radius, String name) {
super(name);
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle has been drawn "); }
@Override
public double area() {
return (double)((pi*radius*radius)/2); }
}
System.out.println(" ");