Advance Programming Class
Advance Programming Class
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. The idea behind inheritance in
Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class also.
}}
In other words, If a subclass provides the specific implementation of the method that has class Bank{
been declared by one of its parent class, it is known as method overriding.
int getRateOfInterest(){return 0;}
Usage of Java Method Overriding
} //Creating child classes.
• Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass. class SBI extends Bank{
class Animal{ class Animal{
String color="white"; void eat(){System.out.println("eating...");}
} }
class Dog extends Animal{ class Dog extends Animal{
String color="black"; void eat(){System.out.println("eating bread...");}
void printColor(){ void bark(){System.out.println("barking...");}
System.out.println(color);//prints color of Dog class void work(){
System.out.println(super.color);//prints color of Animal class super.eat();
} bark();
} }
class TestSuper1{ }
public static void main(String args[]){ class TestSuper2{
Dog d=new Dog(); public static void main(String args[]){
d.printColor(); Dog d=new Dog();
}} d.work();
}}
BCA 6th SEMESTAR | ADVANCE JAVA PROGRAMMING
Super Keyword:
1. super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor. Let's see
a simple example:
Example: TestSuper3.java
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}