hereral/Clara-Training-Data huggingface dataset:
Question: Can you provide an Single Inheritance Example in Java?
Answer: When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.


class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class TestInheritance{  
public static void main(String args[]){  
Dog d=new Dog();  
d.bark();  
d.eat();  
}} 

Output:
barking...
eating...
Question: Can you provide an Multilevel Inheritance Example in Java?
Answer: When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class BabyDog extends Dog{  
void weep(){System.out.println("weeping...");}  
}  
class TestInheritance2{  
public static void main(String args[]){  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}}  

Output:
weeping...
barking...
eating...
Question: Can you provide an Hierarchical Inheritance Example in Java?
Answer: When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class Cat extends Animal{  
void meow(){System.out.println("meowing...");}  
}  
class TestInheritance3{  
public static void main(String args[]){  
Cat c=new Cat();  
c.meow();  
c.eat();  
//c.bark();//C.T.Error  
}}

Output:

meowing...
eating...
Question: Why multiple inheritance is not supported in java?
Answer: As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. For example:

interface Printable{  
void print();  
}  
interface Showable{  
void print();  
}  
  
class TestInterface3 implements Printable, Showable{  
public void print(){System.out.println("Hello");}  
public static void main(String args[]){  
TestInterface3 obj = new TestInterface3();  
obj.print();  
 }  
}  

Output:

Hello
Question: Can you provide an Simple Example of Aggregation?
Answer: In this example, we have created the reference of Operation class in the Circle class.

class Operation{  
 int square(int n){  
  return n*n;  
 }  
}  
  
class Circle{  
 Operation op;//aggregation  
 double pi=3.14;  
    
 double area(int radius){  
   op=new Operation();  
   int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).  
   return pi*rsquare;  
 }  
  
     
    
 public static void main(String args[]){  
   Circle c=new Circle();  
   double result=c.area(5);  
   System.out.println(result);  
 }  
}  

Output:78.5
Question: When use Aggregation?
Answer: -Code reuse is also best achieved by aggregation when there is no is-a relationship.
-Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.
Question: What is Method Overloading in Java?
Answer: If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.
Question: What is the Advantage of method overloading?
Answer: Method overloading increases the readability of the program.

Different ways to overload the method
There are two ways to overload the method in java

1.By changing number of arguments
2.By changing the data type
Question: Why Method Overloading is not possible by changing the return type of method only?
Answer: In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's see how ambiguity may occur:

class Adder{  
static int add(int a,int b){return a+b;}  
static double add(int a,int b){return a+b;}  
}  
class TestOverloading3{  
public static void main(String[] args){  
System.out.println(Adder.add(11,11));//ambiguity  
}}  
Output:

Compile Time Error: method add(int,int) is already defined in class Adder
Question: Can we overload java main() method?
Answer: Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example:

class TestOverloading4{  
public static void main(String[] args){System.out.println("main with String[]");}  
public static void main(String args){System.out.println("main with String");}  
public static void main(){System.out.println("main without args");}  
}  
Output:

main with String[]
Question: What is Method Overloading and Type Promotion?
Answer: One type is promoted to another implicitly if no matching datatype is found.

To understand the concept,  byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int,long,float or double and so on.
Question: Can you provide an Example of Method Overloading with TypePromotion in Java?
Answer: class OverloadingCalculation1{  
  void sum(int a,long b){System.out.println(a+b);}  
  void sum(int a,int b,int c){System.out.println(a+b+c);}  
  
  public static void main(String args[]){  
  OverloadingCalculation1 obj=new OverloadingCalculation1();  
  obj.sum(20,20);//now second int literal will be promoted to long  
  obj.sum(20,20,20);  
  
  }  
}  

Output:40
       60
Question: Can you provide an Example of Method Overloading with Type Promotion if matching found in Java?
Answer: If there are matching type arguments in the method, type promotion is not performed.

class OverloadingCalculation2{  
  void sum(int a,int b){System.out.println("int arg method invoked");}  
  void sum(long a,long b){System.out.println("long arg method invoked");}  
  
  public static void main(String args[]){  
  OverloadingCalculation2 obj=new OverloadingCalculation2();  
  obj.sum(20,20);//now int arg sum() method gets invoked  
  }  
}

Output:int arg method invoked
Question: Can you provide an Example of Method Overloading with Type Promotion in case of ambiguity in Java?
Answer: If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.

class OverloadingCalculation3{  
  void sum(int a,long b){System.out.println("a method invoked");}  
  void sum(long a,int b){System.out.println("b method invoked");}  
  
  public static void main(String args[]){  
  OverloadingCalculation3 obj=new OverloadingCalculation3();  
  obj.sum(20,20);//now ambiguity  
  }  
}  
Output:Compile Time Error
Question: What is Method Overriding in Java?
Answer: If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.
Question: What are the Usage of Java Method Overriding?
Answer: -Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
-Method overriding is used for runtime polymorphism
Question: What are the Rules for Java Method Overriding?
Answer: 1.The method must have the same name as in the parent class
2.The method must have the same parameter as in the parent class.
3.There must be an IS-A relationship (inheritance).
Question: Can you provide an Example of method overriding in Java?
Answer: In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding  
//Creating a parent class.  
class Vehicle{  
  //defining a method  
  void run(){System.out.println("Vehicle is running");}  
}  
//Creating a child class  
class Bike2 extends Vehicle{  
  //defining the same method as in the parent class  
  void run(){System.out.println("Bike is running safely");}  
  
  public static void main(String args[]){  
  Bike2 obj = new Bike2();//creating object  
  obj.run();//calling method  
  }  
}  
Output:

Bike is running safely
Question: Can you provide a real example of Java Method Overriding in Java?
Answer: Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest.

//Java Program to demonstrate the real scenario of Java Method Overriding  
//where three classes are overriding the method of a parent class.  
//Creating a parent class.  
class Bank{  
int getRateOfInterest(){return 0;}  
}  
//Creating child classes.  
class SBI extends Bank{  
int getRateOfInterest(){return 8;}  
}  
  
class ICICI extends Bank{  
int getRateOfInterest(){return 7;}  
}  
class AXIS extends Bank{  
int getRateOfInterest(){return 9;}  
}  
//Test class to create objects and call the methods  
class Test2{  
public static void main(String args[]){  
SBI s=new SBI();  
ICICI i=new ICICI();  
AXIS a=new AXIS();  
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  
}  
}

Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Question: Can we override static method?
Answer: No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.
Question: Why can we not override static method?
Answer: It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area.
Question: Can we override java main method?
Answer: No, because the main is a static method.
Question: What is the Difference between method Overloading and Method Overriding in java?
Answer: There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below:


1)  Method overloading is used to increase the readability of the program while Method overriding is used to provide the specific implementation of the method that is already provided by its super class.

2) Method overloading is performed within class while Method overriding occurs in two classes that have IS-A (inheritance) relationship.

3) In case of method overloading, parameter must be different while In case of method overriding, parameter must be same.

4) Method overloading is the example of compile time polymorphism while Method overriding is the example of run time polymorphism.

5)  In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter while Return type must be same or covariant in method overriding.
Question: What is Covariant Return Type in Java?
Answer: The covariant return type specifies that the return type may vary in the same direction as the subclass.

Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.
Question: Can you provide an Simple example of Covariant Return Type in Java?
Answer:  Let's take a simple example:
FileName: B1.java

class A{    
A get(){return this;}    
}    
    
class B1 extends A{    
@Override  
B1 get(){return this;}    
void message(){System.out.println("welcome to covariant return type");}    
    
public static void main(String args[]){    
new B1().get().message();    
}    
}    
Output:
welcome to covariant return type
Question: What is the Advantages of Covariant Return Type in Java?
Answer: Following are the advantages of the covariant return type.

1) Covariant return type assists to stay away from the confusing type casts in the class hierarchy and makes the code more usable, readable, and maintainable.

2) In the method overriding, the covariant return type provides the liberty to have more to the point return types.

3) Covariant return type helps in preventing the run-time ClassCastExceptions on returns.

Let's take an example to understand the advantages of the covariant return type.
Question: How is Covariant return types implemented?
Answer: Java doesn't allow the return type-based overloading, but JVM always allows return type-based overloading. JVM uses the full signature of a method for lookup/resolution. Full signature means it includes return type in addition to argument types. i.e., a class can have two or more methods differing only by return type. javac uses this fact to implement covariant return types.
Output:

The number 1 is not the powerful number.
The number 2 is not the powerful number.
The number 3 is not the powerful number.
The number 4 is the powerful number.
The number 5 is not the powerful number.
The number 6 is not the powerful number.
The number 7 is not the powerful number.
The number 8 is the powerful number.
The number 9 is the powerful number.
The number 10 is not the powerful number.
The number 11 is not the powerful number.
The number 12 is not the powerful number.
The number 13 is not the powerful number.
The number 14 is not the powerful number.
The number 15 is not the powerful number.
The number 16 is the powerful number.
The number 17 is not the powerful number.
The number 18 is not the powerful number.
The number 19 is not the powerful number.
The number 20 is the powerful number.
Question: What is Super Keyword in Java?
Answer: The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.
Question: What are the Usage of Java super Keyword?
Answer: 1.super can be used to refer immediate parent class instance variable.
2.super can be used to invoke immediate parent class method.
3.super() can be used to invoke immediate parent class constructor.
Question: Can you provide an example of super can be used to invoke parent class method in Java?
Answer: The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.

class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void eat(){System.out.println("eating bread...");}  
void bark(){System.out.println("barking...");}  
void work(){  
super.eat();  
bark();  
}  
}  
class TestSuper2{  
public static void main(String args[]){  
Dog d=new Dog();  
d.work();  
}}  
Output:

eating...
barking...
Question: Can you provide an example of super is used to invoke parent class constructor in Java?
Answer: The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:
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();  
}}  
Output:

animal is created
dog is created
Question: Can you provide a super example: real use in Java?
Answer: Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person will be inherited to Emp by default. To initialize all the property, we are using parent class constructor from child class. In such way, we are reusing the parent class constructor.

class Person{  
int id;  
String name;  
Person(int id,String name){  
this.id=id;  
this.name=name;  
}  
}  
class Emp extends Person{  
float salary;  
Emp(int id,String name,float salary){  
super(id,name);//reusing parent constructor  
this.salary=salary;  
}  
void display(){System.out.println(id+" "+name+" "+salary);}  
}  
class TestSuper5{  
public static void main(String[] args){  
Emp e1=new Emp(1,"ankit",45000f);  
e1.display();  
}}  
Output:

1 ankit 45000
Question: What is Instance initializer block in Java?
Answer: Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
The initialization of the instance variable can be done directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
Question: Why use instance initializer block?
Answer: Suppose I have to perform some operations while assigning value to instance data member e.g. a for loop to fill a complex array or error handling etc.
Question: Can you provide an Example of instance initializer block in Java?
Answer: Let's see the simple example of instance initializer block that performs initialization.
class Bike7{  
    int speed;  
      
    Bike7(){System.out.println("speed is "+speed);}  
   
    {speed=100;}  
       
    public static void main(String args[]){  
    Bike7 b1=new Bike7();  
    Bike7 b2=new Bike7();  
    }      
}  
Output:speed is 100
       speed is 100
Question: What is invoked first, instance initializer block or constructor?
Answer: class Bike8{  
    int speed;  
      
    Bike8(){System.out.println("constructor is invoked");}  
   
    {System.out.println("instance initializer block invoked");}  
       
    public static void main(String args[]){  
    Bike8 b1=new Bike8();  
    Bike8 b2=new Bike8();  
    }      
}  
Output:instance initializer block invoked
       constructor is invoked
       instance initializer block invoked
       constructor is invoked
Question: What are the Rules for instance initializer block in Java?
Answer: There are mainly three rules for the instance initializer block. They are as follows:
The instance initializer block is created when instance of the class is created.
The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
The instance initializer block comes in the order in which they appear.
Question: Can you provide an example Program of instance initializer block that is invoked after super()?
Answer: class A{  
A(){  
System.out.println("parent class constructor invoked");  
}  
}  
class B2 extends A{  
B2(){  
super();  
System.out.println("child class constructor invoked");  
}  
  
{System.out.println("instance initializer block is invoked");}  
  
public static void main(String args[]){  
B2 b=new B2();  
}  
}  
Output:parent class constructor invoked
       instance initializer block is invoked
       child class constructor invoked
Question: Can you provid an example of instance block in java?
Answer: class A{  
A(){  
System.out.println("parent class constructor invoked");  
}  
}  
  
class B3 extends A{  
B3(){  
super();  
System.out.println("child class constructor invoked");  
}  
  
B3(int a){  
super();  
System.out.println("child class constructor invoked "+a);  
}  
  
{System.out.println("instance initializer block is invoked");}  
  
public static void main(String args[]){  
B3 b1=new B3();  
B3 b2=new B3(10);  
}  
}  
  Output: parent class constructor invoked
       instance initializer block is invoked
       child class constructor invoked
       parent class constructor invoked
       instance initializer block is invoked
       child class constructor invoked 10
Question: What is Final Keyword In Java?
Answer: The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

1.variable
2.method
3.class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.
Question: What is Java final variable?
Answer: If you make any variable as final, you cannot change the value of final variable(It will be constant).
Question: Can you provide an Example of final variable in Java?
Answer: There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.
class Bike9{  
 final int speedlimit=90;//final variable  
 void run(){  
  speedlimit=400;  
 }  
 public static void main(String args[]){  
 Bike9 obj=new  Bike9();  
 obj.run();  
 }  
}//end of class  
Output:Compile Time Error
Question: What is Java final method?
Answer: If you make any method as final, you cannot override it.
Question: Can you provide an Example of final method in Java?
Answer: class Bike{  
  final void run(){System.out.println("running");}  
}  
     
class Honda extends Bike{  
   void run(){System.out.println("running safely with 100kmph");}  
     
   public static void main(String args[]){  
   Honda honda= new Honda();  
   honda.run();  
   }  
}  
Output:Compile Time Error
Question: What is Java final class?
Answer: If you make any class as final, you cannot extend it.
Question: Can you provide an Example of final class in Java?
Answer: final class Bike{}  
  
class Honda1 extends Bike{  
  void run(){System.out.println("running safely with 100kmph");}  
    
  public static void main(String args[]){  
  Honda1 honda= new Honda1();  
  honda.run();  
  }  
}  
Output:Compile Time Error
Question: Is final method inherited?
Answer:  Yes, final method is inherited but you cannot override it. For Example:
class Bike{  
  final void run(){System.out.println("running...");}  
}  
class Honda2 extends Bike{  
   public static void main(String args[]){  
    new Honda2().run();  
   }  
}  
Output:running...
Question: What is blank or uninitialized final variable?
Answer: A final variable that is not initialized at the time of declaration is known as blank final variable.

If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.
Question: Can you provide an Example of blank final variable in Java?
Answer: class Student{  
int id;  
String name;  
final String PAN_CARD_NUMBER;  
...  
}
Question: What is static blank final variable?
Answer: A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
Question: Can you provide an Example of static blank final variable in Java?
Answer: class A{  
  static final int data;//static blank final variable  
  static{ data=50;}  
  public static void main(String args[]){  
    System.out.println(A.data);  
 }  
}
Question: Can we declare a constructor final?
Answer: No, because constructor is never inherited.
Question: What is Polymorphism in Java?
Answer: Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.
Question: What is Runtime Polymorphism in Java?
Answer: Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.
 
class A{}  
class B extends A{}  
A a=new B();//upcasting  

For upcasting, we can use the reference variable of class type or an interface type. 
For Example:

interface I{}  
class A{}  
class B extends A implements I{}  

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A Object.
Question: Can you provide an Example of Java Runtime Polymorphism?
Answer: In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

class Bike{  
  void run(){System.out.println("running");}  
}  
class Splendor extends Bike{  
  void run(){System.out.println("running safely with 60km");}  
  
  public static void main(String args[]){  
    Bike b = new Splendor();//upcasting  
    b.run();  
  }  
} 


Output:
running safely with 60km.
Question: Can you provide a Java Runtime Polymorphism Example: Bank?
Answer: Consider a scenario where Bank is a class that provides a method to get the rate of interest. However, the rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.

class Bank{  
float getRateOfInterest(){return 0;}  
}  
class SBI extends Bank{  
float getRateOfInterest(){return 8.4f;}  
}  
class ICICI extends Bank{  
float getRateOfInterest(){return 7.3f;}  
}  
class AXIS extends Bank{  
float getRateOfInterest(){return 9.7f;}  
}  
class TestPolymorphism{  
public static void main(String args[]){  
Bank b;  
b=new SBI();  
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());  
b=new ICICI();  
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());  
b=new AXIS();  
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());  
}  
}  


Output:

SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
Question: Can you provide an Java Runtime Polymorphism Example: Shape?
Answer: class Shape{  
void draw(){System.out.println("drawing...");}  
}  
class Rectangle extends Shape{  
void draw(){System.out.println("drawing rectangle...");}  
}  
class Circle extends Shape{  
void draw(){System.out.println("drawing circle...");}  
}  
class Triangle extends Shape{  
void draw(){System.out.println("drawing triangle...");}  
}  
class TestPolymorphism2{  
public static void main(String args[]){  
Shape s;  
s=new Rectangle();  
s.draw();  
s=new Circle();  
s.draw();  
s=new Triangle();  
s.draw();  
}  
}  
Output:

drawing rectangle...
drawing circle...
drawing triangle...
Question: Can you provide a Java Runtime Polymorphism Example: Animal?
Answer: class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void eat(){System.out.println("eating bread...");}  
}  
class Cat extends Animal{  
void eat(){System.out.println("eating rat...");}  
}  
class Lion extends Animal{  
void eat(){System.out.println("eating meat...");}  
}  
class TestPolymorphism3{  
public static void main(String[] args){  
Animal a;  
a=new Dog();  
a.eat();  
a=new Cat();  
a.eat();  
a=new Lion();  
a.eat();  
}}  
Output:
eating bread...
eating rat...
eating meat...
Question: What is Java Runtime Polymorphism with Data Member?
Answer: A method is overridden, not the data members, so runtime polymorphism can't be achieved by data members.

In the example given below, both the classes have a data member speedlimit. We are accessing the data member by the reference variable of Parent class which refers to the subclass object. Since we are accessing the data member which is not overridden, hence it will access the data member of the Parent class always.
Question: What is Java Runtime Polymorphism with Multilevel Inheritance?
Answer: Let's see the simple example of Runtime Polymorphism with multilevel inheritance.

class Animal{  
void eat(){System.out.println("eating");}  
}  
class Dog extends Animal{  
void eat(){System.out.println("eating fruits");}  
}  
class BabyDog extends Dog{  
void eat(){System.out.println("drinking milk");}  
public static void main(String args[]){  
Animal a1,a2,a3;  
a1=new Animal();  
a2=new Dog();  
a3=new BabyDog();  
a1.eat();  
a2.eat();  
a3.eat();  
}  
}  
Output:

eating
eating fruits
drinking Milk
Question: What is Static Binding and Dynamic Binding?
Answer: Connecting a method call to the method body is known as binding.

There are two types of binding

1.Static Binding (also known as Early Binding).
2.Dynamic Binding (also known as Late Binding).
Question: Does variables have a type in Java?
Answer: Each variable has a type, it may be primitive and non-primitive.
int data=30;
Question: Does References have a type in Java?

Answer: class Dog{  
 public static void main(String args[]){  
  Dog d1;//Here d1 is a type of Dog  
 }  
}
Question: Doese Objects have a type in java?
Answer: An object is an instance of particular java class,but it is also an instance of its superclass.
class Animal{}  
  
class Dog extends Animal{  
 public static void main(String args[]){  
  Dog d1=new Dog();  
 }  
}
Question: What is static binding?
Answer: When type of the object is determined at compiled time(by the compiler), it is known as static binding.

If there is any private, final or static method in a class, there is static binding.
Question: Can you provide an Example of static binding in Java?
Answer: class Dog{  
 private void eat(){System.out.println("dog is eating...");}  
  
 public static void main(String args[]){  
  Dog d1=new Dog();  
  d1.eat();  
 }  
}
Question: What is Dynamic binding ?
Answer: When type of the object is determined at run-time, it is known as dynamic binding.
Question: Can you provide an Example of dynamic binding in Java?
Answer: class Animal{  
 void eat(){System.out.println("animal is eating...");}  
}  
  
class Dog extends Animal{  
 void eat(){System.out.println("dog is eating...");}  
  
 public static void main(String args[]){  
  Animal a=new Dog();  
  a.eat();  
 }  
}  
Output:dog is eating...
Question: What is Java instanceof?
Answer: The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).

The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.
Question: Can you provide a Simple example of java instanceof?
Answer: Let's see the simple example of instance operator where it tests the current class.

class Simple1{  
 public static void main(String args[]){  
 Simple1 s=new Simple1();  
 System.out.println(s instanceof Simple1);//true  
 }  
}  
Output:true
Question: Can you provide Another example of java instanceof operator?
Answer: class Animal{}  
class Dog1 extends Animal{//Dog inherits Animal  
  
 public static void main(String args[]){  
 Dog1 d=new Dog1();  
 System.out.println(d instanceof Animal);//true  
 }  
}
Question: Can you provide a example instanceof in java with a variable that have null value?
Answer: If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given below where we apply instanceof operator with the variable that have null value.

class Dog2{  
 public static void main(String args[]){  
  Dog2 d=null;  
  System.out.println(d instanceof Dog2);//false  
 }  
}  
Output:false
Question: What is Downcasting with java instanceof operator?
Answer: When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible.

Dog d=new Animal();//Compilation error  
If we perform downcasting by typecasting, ClassCastException is thrown at runtime.

Dog d=(Dog)new Animal();  
//Compiles successfully but ClassCastException is thrown at runtime
Question: What is Possibility of downcasting with instanceof?
Answer: Let's see the example, where downcasting is possible by instanceof operator.

class Animal { }  
  
class Dog3 extends Animal {  
  static void method(Animal a) {  
    if(a instanceof Dog3){  
       Dog3 d=(Dog3)a;//downcasting  
       System.out.println("ok downcasting performed");  
    }  
  }  
   
  public static void main (String [] args) {  
    Animal a=new Dog3();  
    Dog3.method(a);  
  }  
    
 }  
Output:ok downcasting performed
Question: How to downcast without the use of java instanceof
Answer: Downcasting can also be performed without the use of instanceof operator as displayed in the following example:

class Animal { }  
class Dog4 extends Animal {  
  static void method(Animal a) {  
       Dog4 d=(Dog4)a;//downcasting  
       System.out.println("ok downcasting performed");  
  }  
   public static void main (String [] args) {  
    Animal a=new Dog4();  
    Dog4.method(a);  
  }  
}  
Output:ok downcasting performed
Question: How to understand Real use of instanceof in java?
Answer: Let's see the real use of instanceof keyword by the example given below.

interface Printable{}  
class A implements Printable{  
public void a(){System.out.println("a method");}  
}  
class B implements Printable{  
public void b(){System.out.println("b method");}  
}  
  
class Call{  
void invoke(Printable p){//upcasting  
if(p instanceof A){  
A a=(A)p;//Downcasting   
a.a();  
}  
if(p instanceof B){  
B b=(B)p;//Downcasting   
b.b();  
}  
  
}  
}//end of Call class  
  
class Test4{  
public static void main(String args[]){  
Printable p=new B();  
Call c=new Call();  
c.invoke(p);  
}  
}  
Output: b method
Question: What is Abstract class in Java?
Answer: A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.
Question: What is Abstraction in Java?
Answer: Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery.
Question: What is Abstract Method in Java?
Answer: A method which is declared as abstract and does not have implementation is known as an abstract method.

Example of abstract method

abstract void printStatus();//no method body and abstract
Question: Can you provide an Example of Abstract class that has an abstract method?
Answer: In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by the Honda class.

abstract class Bike{  
  abstract void run();  
}  
class Honda4 extends Bike{  
void run(){System.out.println("running safely");}  
public static void main(String args[]){  
 Bike obj = new Honda4();  
 obj.run();  
}  
}  
Output:running safely
Question: How to understand the real scenario of Abstract class in Java?
Answer: In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user), and an object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about the factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked.

File: TestAbstraction1.java

abstract class Shape{  
abstract void draw();  
}  
//In real scenario, implementation is provided by others i.e. unknown by end user  
class Rectangle extends Shape{  
void draw(){System.out.println("drawing rectangle");}  
}  
class Circle1 extends Shape{  
void draw(){System.out.println("drawing circle");}  
}  
//In real scenario, method is called by programmer or user  
class TestAbstraction1{  
public static void main(String args[]){  
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method  
s.draw();  
}  
}  
Output: drawing circle
Question: Can you provide Another example of Abstract class in java?
Answer: abstract class Bank{    
abstract int getRateOfInterest();    
}    
class SBI extends Bank{    
int getRateOfInterest(){return 7;}    
}    
class PNB extends Bank{    
int getRateOfInterest(){return 8;}    
}    
    
class TestBank{    
public static void main(String args[]){    
Bank b;  
b=new SBI();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
b=new PNB();  
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
}}    
Output: Rate of Interest is: 7 %
Rate of Interest is: 8 %
Question: Can you provide an example of Abstract class having constructor, data member and methods?

Answer: An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and even main() method.

File: TestAbstraction2.java

//Example of an abstract class that has abstract and non-abstract methods  
 abstract class Bike{  
   Bike(){System.out.println("bike is created");}  
   abstract void run();  
   void changeGear(){System.out.println("gear changed");}  
 }  
//Creating a Child class which inherits Abstract class  
 class Honda extends Bike{  
 void run(){System.out.println("running safely..");}  
 }  
//Creating a Test class which calls abstract and non-abstract methods  
 class TestAbstraction2{  
 public static void main(String args[]){  
  Bike obj = new Honda();  
  obj.run();  
  obj.changeGear();  
 }  
}  
  Output: bike is created
       running safely..
       gear changed
Question: What is Interface in Java?
Answer: An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.
Question: Why use Java interface?
Answer: There are mainly three reasons to use interface. They are given below.

-It is used to achieve abstraction.
-By interface, we can support the functionality of multiple inheritance.
-It can be used to achieve loose coupling.
Question: How to declare an interface?
Answer: An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.
Question: Can you provide Java Interface Example?
Answer: In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.

interface printable{  
void print();  
}  
class A6 implements printable{  
public void print(){System.out.println("Hello");}  
  
public static void main(String args[]){  
A6 obj = new A6();  
obj.print();  
 }  
}  
Output: Hello
Question: Can you provide Java Interface Example: Drawable?
Answer: In this example, the Drawable interface has only one method. Its implementation is provided by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its implementation is provided by different implementation providers. Moreover, it is used by someone else. The implementation part is hidden by the user who uses the interface.

File: TestInterface1.java

//Interface declaration: by first user  
interface Drawable{  
void draw();  
}  
//Implementation: by second user  
class Rectangle implements Drawable{  
public void draw(){System.out.println("drawing rectangle");}  
}  
class Circle implements Drawable{  
public void draw(){System.out.println("drawing circle");}  
}  
//Using interface: by third user  
class TestInterface1{  
public static void main(String args[]){  
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()  
d.draw();  
}}  
Output:
drawing circle
Question: Can you provide Java Interface Example: Bank?
Answer: Let's see another example of java interface which provides the implementation of Bank interface.

File: TestInterface2.java

interface Bank{  
float rateOfInterest();  
}  
class SBI implements Bank{  
public float rateOfInterest(){return 9.15f;}  
}  
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());  
}}  
Output:
ROI: 9.15
Question: Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
Answer: As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. For example:

interface Printable{  
void print();  
}  
interface Showable{  
void print();  
}  
  
class TestInterface3 implements Printable, Showable{  
public void print(){System.out.println("Hello");}  
public static void main(String args[]){  
TestInterface3 obj = new TestInterface3();  
obj.print();  
 }  
}  
Output:

Hello
Question: What is Interface inheritance?
Answer: A class implements an interface, but one interface extends another interface.
Question: Can you provide Java 8 Default Method in Interface?
Answer: Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an example:
interface Drawable{  
void draw();  
default void msg(){System.out.println("default method");}  
}  
class Rectangle implements Drawable{  
public void draw(){System.out.println("drawing rectangle");}  
}  
class TestInterfaceDefault{  
public static void main(String args[]){  
Drawable d=new Rectangle();  
d.draw();  
d.msg();  
}}  interface Drawable{  
void draw();  
default void msg(){System.out.println("default method");}  
}  
class Rectangle implements Drawable{  
public void draw(){System.out.println("drawing rectangle");}  
}  
class TestInterfaceDefault{  
public static void main(String args[]){  
Drawable d=new Rectangle();  
d.draw();  
d.msg();  
}}  
Output:

drawing rectangle
default method
Question: Can you provide Java 8 Static Method in Interface?
Answer: ince Java 8, we can have static method in interface. Let's see an example:
interface Drawable{  
void draw();  
static int cube(int x){return x*x*x;}  
}  
class Rectangle implements Drawable{  
public void draw(){System.out.println("drawing rectangle");}  
}  
  
class TestInterfaceStatic{  
public static void main(String args[]){  
Drawable d=new Rectangle();  
d.draw();  
System.out.println(Drawable.cube(3));  
}}  
Output:

drawing rectangle
27
Question:  What is marker or tagged interface?
Answer: An interface which has no member is known as a marker or tagged interface, for example, Serializable, Cloneable, Remote, etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.

//How Serializable interface is written?  
public interface Serializable{  
}
Question: What is Nested Interface in Java?
Answer: Note: An interface can have another interface which is known as a nested interface. We will learn it in detail in the nested classes chapter. For example:

interface printable{  
 void print();  
 interface MessagePrintable{  
   void msg();  
 }  
}
Question: Can you provide an Example of abstract class and interface in Java?
Answer: Let's see a simple example where we are using interface and abstract class both.
//Creating interface that has 4 methods  
interface A{  
void a();//bydefault, public and abstract  
void b();  
void c();  
void d();  
}  
  
//Creating abstract class that provides the implementation of one method of A interface  
abstract class B implements A{  
public void c(){System.out.println("I am C");}  
}  
  
//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods  
class M extends B{  
public void a(){System.out.println("I am a");}  
public void b(){System.out.println("I am b");}  
public void d(){System.out.println("I am d");}  
}  
  
//Creating a test class that calls the methods of A interface  
class Test5{  
public static void main(String args[]){  
A a=new M();  
a.a();  
a.b();  
a.c();  
a.d();  
}}  
Output:

       I am a
       I am b
       I am c
       I am d
Question: What is Java Package?
Answer: A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Question: What is the Advantage of Java Package?
Answer: 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.
Question: Can you provide Simple example of java package?
Answer: The package keyword is used to create a package in java.

//save as Simple.java  
package mypack;  
public class Simple{  
 public static void main(String args[]){  
    System.out.println("Welcome to package");  
   }  
}