52) What are the advantages of passing this into a method instead of the current class object itself?
As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.
- this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
- this can be used in the synchronized block.
53) What is the Inheritance?
Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. 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. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
There are five types of inheritance in Java.
- Single-level inheritance
- Multi-level inheritance
- Multiple Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
Multiple inheritance is not supported in Java through class.
54) Why is Inheritance used in Java?
There are various advantages of using inheritance in Java that is given below.
- Inheritance provides code reusability. The derived class does not need to redefine the method of base class unless it needs to provide the specific implementation of the method.
- Runtime polymorphism cannot be achieved without using inheritance.
- We can simulate the inheritance of classes with the real-time objects which makes OOPs more realistic.
- Inheritance provides data hiding. The base class can hide some data from the derived class by making it private.
- Method overriding cannot be achieved without inheritance. By method overriding, we can give a specific implementation of some basic method contained by the base class.
55) Which class is the superclass for all the classes?
The object class is the superclass of all other classes in Java.
56) Why is multiple inheritance not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.
Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();
12. }
13. }
Compile Time Error
57) What is aggregation?
Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.
Address.java
1. public class Address {
2. String city,state,country;
3.
4. public Address(String city, String state, String country) {
5. this.city = city;
6. this.state = state;
7. this.country = country;
8. }
9.
10. }
Employee.java
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. this.id = id;
8. this.name = name;
9. this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("ONG","AP","india");
19. Address address2=new Address("NLR","AP","india");
20.
21. Emp e=new Emp(504,"NAGA",address1);
22. Emp e2=new Emp(505,"RAJESH",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }
Output
504 NAGA
ONG AP india
NLR RAJESH
NLR AP india
58) What is composition?
Holding the reference of a class within some other class is known as composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. In other words, we can say that composition is the particular case of aggregation which represents a stronger relationship between two objects. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.
59) What is the difference between aggregation and composition?
Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).
60) Why does Java not support pointers?
The pointer is a variable that refers to the memory address. They are not used in Java because they are unsafe(unsecured) and complex to understand.
61) What is super in java?
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }
13. }
Output:
animal is created
dog is created
62) How can constructor chaining be done by using the super keyword?
1. class Person
2. {
3. String name,address;
4. int age;
5. public Person(int age, String name, String address)
6. {
7. this.age = age;
8. this.name = name;
9. this.address = address;
10. }
11. }
12. class Employee extends Person
13. {
14. float salary;
15. public Employee(int age, String name, String address, float salary)
16. {
17. super(age,name,address);
18. this.salary = salary;
19. }
20. }
21. public class Test
22. {
23. public static void main (String args[])
24. {
25. Employee e = new Employee(22, "RAJESH", "ONG", 90000);
26. System.out.println("Name: "+e.name+" Salary: "+e.salary+" Age: "+e.age+" Address: "+e.address);
27. }
28. }
Output
Name: RAJESH Salary: 90000.0 Age: 22 Address: ONG
63) What are the main uses of the super keyword?
There are the following uses of super keyword.
- super can be used to refer to the immediate parent class instance variable.
- super can be used to invoke the immediate parent class method.
- super() can be used to invoke immediate parent class constructor.
64) What are the differences between this and super keyword?
There are the following differences between this and super keyword.
- The super keyword always points to the parent class contexts whereas this keyword always points to the current class context.
- The super keyword is primarily used for initializing the base class variables within the derived class constructor whereas this keyword primarily used to differentiate between local and instance variables when passed in the class constructor.
- The super and this must be the first statement inside constructor otherwise the compiler will throw an error.
65) What is the output of the following Java program?
1. class Person
2. {
3. public Person()
4. {
5. System.out.println("Person class constructor called");
6. }
7. }
8. public class Employee extends Person
9. {
10. public Employee()
11. {
12. System.out.println("Employee class constructor called");
13. }
14. public static void main (String args[])
15. {
16. Employee e = new Employee();
17. }
18. }
Output
Person class constructor called
Employee class constructor called
Explanation
The super() is implicitly invoked by the compiler if no super() or this() is included explicitly within the derived class constructor. Therefore, in this case, The Person class constructor is called first and then the Employee class constructor is called.
66) Can you use this() and super() both in a constructor?
No, because this() and super() must be the first statement in the class constructor.
Example:
1. public class Test{
2. Test()
3. {
4. super();
5. this();
6. System.out.println("Test class object is created");
7. }
8. public static void main(String []args){
9. Test t = new Test();
10. }
11. }
Output:
Test.java:5: error: call to this must be first statement in constructor
67)What is object cloning?
The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
protected Object clone() throws CloneNotSupportedException
68) What is method overloading?
Method overloading is the polymorphism technique which allows us to create multiple methods with the same name but different signature. We can achieve method overloading in two ways.
- Changing the number of arguments
- Changing the return type
Method overloading increases the readability of the program. Method overloading is performed to figure out the program quickly.
69) Why is method overloading not possible by changing the return type in java?
In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. }}
Output:
Compile Time Error: method add(int, int) is already defined in class Adder
70) Can we overload the methods by making them static?
No, We cannot overload the methods by just applying the static keyword to them(number of parameters and types are the same). Consider the following example.
1. public class Animal
2. {
3. void consume(int a)
4. {
5. System.out.println(a+" consumed!!");
6. }
7. static void consume(int a)
8. {
9. System.out.println("consumed static "+a);
10. }
11. public static void main (String args[])
12. {
13. Animal a = new Animal();
14. a.consume(10);
15. Animal.consume(20);
16. }
17. }
Output
Animal.java:7: error: method consume(int) is already defined in class Animal
static void consume(int a)
^
Animal.java:15: error: non-static method consume(int) cannot be referenced from a static context
Animal.consume(20);
^
2 errors
71) Can we overload the main() method?
Yes, we can have any number of main methods in a Java program by using method overloading.
72) What is method overloading with type promotion?
By Type promotion is method overloading, we mean that one data type can be promoted to another implicitly if no exact matching is found.
As displayed in the above diagram, the 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. Consider the following example.
1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. obj.sum(20,20);
8. obj.sum(20,20,20);
9. }
10. }
Output
40
60
73) What is the output of the following Java program?
1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);
8. }
9. }
Output
OverloadingCalculation3.java:7: error: reference to sum is ambiguous
obj.sum(20,20);//now ambiguity
^
both method sum(int,long) in OverloadingCalculation3
and method sum(long,int) in OverloadingCalculation3 match
1 error
Explanation
There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the case of ambiguity. Therefore, the compiler will throw an error.
74) What is method overriding:
If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the interface methods.
Rules for Method overriding
- The method must have the same name as in the parent class.
- The method must have the same signature as in the parent class.
- Two classes must have an IS-A relationship between them.
75) Can we override the static method?
No, you can't override the static method because they are the part of the class, not the object.
76) Why can we not override static method?
It is because the static method is the part of the class, and it is bound with class whereas instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.
77) Can we override the overloaded method?
Yes.
78) Difference between method Overloading and Overriding.
Method Overloading
|
Method Overriding
|
1) Method overloading increases the readability of the program.
|
Method overriding provides the specific implementation of the method that is already provided by its superclass.
|
2) Method overloading occurs within the class.
|
Method overriding occurs in two classes that have IS-A relationship between them.
|
3) In this case, the parameters must be different.
|
In this case, the parameters must be the same.
|
79) Can we override the private methods?
No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.
80) Can we change the scope of the overridden method in the subclass?
Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.
- The private can be changed to protected, public, or default.
- The protected can be changed to public or default.
- The default can be changed to public.
- The public will always remain public.
81) Can we modify the throws clause of the superclass method while overriding it in the subclass?
Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.
- If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
- If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
82) What is the output of the following Java program?
1. class Base
2. {
3. void method(int a)
4. {
5. System.out.println("Base class method called with integer a = "+a);
6. }
7.
8. void method(double d)
9. {
10. System.out.println("Base class method called with double d ="+d);
11. }
12. }
13.
14. class Derived extends Base
15. {
16. @Override
17. void method(double d)
18. {
19. System.out.println("Derived class method called with double d ="+d);
20. }
21. }
22.
23. public class Main
24. {
25. public static void main(String[] args)
26. {
27. new Derived().method(10);
28. }
29. }
Output
Base class method called with integer a = 10
Explanation
The method() is overloaded in class Base whereas it is derived in class Derived with the double type as the parameter. In the method call, the integer is passed.
83) Can you have virtual functions in Java?
Yes, all functions in Java are virtual by default.
84) What is covariant return type?
Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.
1. class A{
2. A get(){return this;}
3. }
4.
5. class B1 extends A{
6. B1 get(){return this;}
7. void message(){System.out.println("welcome to covariant return type");}
8.
9. public static void main(String args[]){
10. new B1().get().message();
11. }
12. }
Output: welcome to covariant return type
85) What is the output of the following Java program?
1. class Base
2. {
3. public void baseMethod()
4. {
5. System.out.println("BaseMethod called ...");
6. }
7. }
8. class Derived extends Base
9. {
10. public void baseMethod()
11. {
12. System.out.println("Derived method called ...");
13. }
14. }
15. public class Test
16. {
17. public static void main (String args[])
18. {
19. Base b = new Derived();
20. b.baseMethod();
21. }
22. }
Output
Derived method called ...
Explanation
The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is achieved between class Base and Derived. At compile time, the presence of method baseMethod checked in Base class, If it presence then the program compiled otherwise the compiler error will be shown. In this case, baseMethod is present in Base class; therefore, it is compiled successfully. However, at runtime, It checks whether the baseMethod has been overridden by Derived class, if so then the Derived class method is called otherwise Base class method is called. In this case, the Derived class overrides the baseMethod; therefore, the Derived class method is called.
86) What is the final variable?
In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.
1. class Bike9{
2. final int speedlimit=90;
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }
Output:Compile Time Error
87) What is the final method?
If we change any method to a final method, we can't override it.
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Output:Compile Time Error
88) What is the final class?
If we make any class final, we can't inherit it into any of the subclasses.
1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Output:Compile Time Error
89) What is the final blank variable?
A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number. Consider the following example:
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
90) Can we initialize the final blank variable?
Yes, if it is not static, we can initialize it in the constructor. If it is static blank final variable, it can be initialized only in the static block.
91) Can you declare the main method as final?
Yes, We can declare the main method as public static final void main(String[] args){}.
92) What is the output of the following Java program?
1. class Main {
2. public static void main(String args[]){
3. final int i;
4. i = 20;
5. System.out.println(i);
6. }
7. }
Output
20
Explanation
Since i is the blank final variable. It can be initialized only once. We have initialized it to 20. Therefore, 20 will be printed.
93) What is the output of the following Java program?
1. class Base
2. {
3. protected final void getInfo()
4. {
5. System.out.println("method of Base class");
6. }
7. }
8.
9. public class Derived extends Base
10. {
11. protected final void getInfo()
12. {
13. System.out.println("method of Derived class");
14. }
15. public static void main(String[] args)
16. {
17. Base obj = new Base();
18. obj.getInfo();
19. }
20. }
Output
Derived.java:11: error: getInfo() in Derived cannot override getInfo() in Base
protected final void getInfo()
^
overridden method is final
1 error
Explanation
The getDetails() method is final; therefore it can not be overridden in the subclass.
94) Can we declare a constructor as final?
The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.
95) Can we declare an interface as final?
No, we cannot declare an interface as final because the interface must be implemented by some class to provide its definition. Therefore, there is no sense to make an interface final. However, if you try to do so, the compiler will show an error.
96) What is the difference between the final method and abstract method?
The main difference between the final method and abstract method is that the abstract method cannot be final as we need to override them in the subclass to give its definition.
97) What is the difference between compile-time polymorphism and runtime polymorphism?
There are the following differences between compile-time polymorphism and runtime polymorphism.
SN
|
compile-time polymorphism
|
Runtime polymorphism
|
1
|
In compile-time polymorphism, call to a method is resolved at compile-time.
|
In runtime polymorphism, call to an overridden method is resolved at runtime.
|
2
|
It is also known as static binding, early binding, or overloading.
|
It is also known as dynamic binding, late binding, overriding, or dynamic method dispatch.
|
3
|
Overloading is a way to achieve compile-time polymorphism in which, we can define multiple methods or constructors with different signatures.
|
Overriding is a way to achieve runtime polymorphism in which, we can redefine some particular method or variable in the derived class. By using overriding, we can give some specific implementation to the base class properties in the derived class.
|
4
|
It provides fast execution because the type of an object is determined at compile-time.
|
It provides slower execution as compare to compile-time because the type of an object is determined at run-time.
|
5
|
Compile-time polymorphism provides less flexibility because all the things are resolved at compile-time.
|
Run-time polymorphism provides more flexibility because all the things are resolved at runtime.
|
98) What is Runtime Polymorphism?
Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at 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.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6. public static void main(String args[]){
7. Bike b = new Splendor();
8. b.run();
9. }
10. }
running safely with 60km.
99) Can you achieve Runtime Polymorphism by data members?
No, because method overriding is used to achieve runtime polymorphism and data members cannot be overridden. We can override the member functions but not the data members. Consider the example given below.
1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6. public static void main(String args[]){
7. Bike obj=new Honda3();
8. System.out.println(obj.speedlimit);
9. }
Output:90
100) What is the difference between static binding and dynamic binding?
In case of the static binding, the type of the object is determined at compile-time whereas, in the dynamic binding, the type of the object is determined at runtime.
Static Binding
1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }
Dynamic Binding
1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
101) What is the output of the following Java program?
1. class BaseTest
2. {
3. void print()
4. {
5. System.out.println("BaseTest:print() called");
6. }
7. }
8. public class Test extends BaseTest
9. {
10. void print()
11. {
12. System.out.println("Test:print() called");
13. }
14. public static void main (String args[])
15. {
16. BaseTest b = new Test();
17. b.print();
18. }
19. }
Output
Test:print() called
Explanation
It is an example of Dynamic method dispatch. The type of reference variable b is determined at runtime. At compile-time, it is checked whether that method is present in the Base class. In this case, it is overridden in the child class, therefore, at runtime the derived class method is called.
102) What is Java instanceOf operator?
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 a null value, it returns false. Consider the following example.
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);
5. }
6. }
Output
true
103) What is the abstraction?
Abstraction is a process of hiding the implementation details and showing only functionality to the user. It displays just the essential things to the user and hides the internal information, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction enables you to focus on what the object does instead of how it does it. Abstraction lets you focus on what the object does instead of how it does it.
In Java, there are two ways to achieve the abstraction.
104) What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.
105) What is the abstract class?
A class that is declared as abstract is known as an abstract class. It needs to be extended and its method implemented. It cannot be instantiated. It can have abstract methods, non-abstract methods, constructors, and static methods. It can also have the final methods which will force the subclass not to change the body of the method. Consider the following example.
1. abstract class Bike{
2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
Output
running safely
106) Can there be an abstract method without an abstract class?
No, if there is an abstract method in a class, that class must be abstract.
107) Is the following program written correctly? If yes then what will be the output of the program?
1. abstract class Calculate
2. {
3. abstract int multiply(int a, int b);
4. }
5.
6. public class Main
7. {
8. public static void main(String[] args)
9. {
10. int result = new Calculate()
11. {
12. @Override
13. int multiply(int a, int b)
14. {
15. return a*b;
16. }
17. }.multiply(12,32);
18. System.out.println("result = "+result);
19. }
20. }
Yes, the program is written correctly. The Main class provides the definition of abstract method multiply declared in abstract class Calculation. The output of the program will be:
Output
384
108) Can you use abstract and final both with a method?
No, because we need to override the abstract method to provide its implementation, whereas we can't override the final method.
109) Is it possible to instantiate the abstract class?
No, the abstract class can never be instantiated even if it contains a constructor and all of its methods are implemented.
110) What is the interface?
The interface is a blueprint for a class that has static constants and abstract methods. It can be used to achieve full abstraction and multiple inheritance. It 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. Java Interface also represents the IS-A relationship. It cannot be instantiated just like the abstract class. However, we need to implement it to define its methods. Since Java 8, we can have the default, static, and private methods in an interface.
111) Can you declare an interface method static?
No, because methods of an interface are abstract by default, and we
can not use static and abstract together.
112) Can the Interface be final?
No, because an interface needs to be implemented by the other class
and if it is final, it can't be implemented by any class.
113) What is a marker interface?
A Marker interface can be defined as the interface which has no data
member and member functions. For example, Serializable, Cloneable are marker
interfaces. The marker interface can be declared as follows.
1. public interface Serializable{
2. }
114) What are the differences between abstract class and interface?
|
Abstract class
|
Interface
|
|
An abstract
class can have a method body (non-abstract methods).
|
The
interface has only abstract methods.
|
|
An abstract
class can have instance variables.
|
An interface
cannot have instance variables.
|
|
An abstract
class can have the constructor.
|
The
interface cannot have the constructor.
|
|
An abstract
class can have static methods.
|
The interface
cannot have static methods.
|
|
You can
extend one abstract class.
|
You can
implement multiple interfaces.
|
|
The abstract
class can provide the
implementation of the interface.
|
The
Interface can't provide the
implementation of the abstract class.
|
|
The abstract keyword is used
to declare an abstract class.
|
The interface keyword is
used to declare an interface.
|
|
An abstract class can
extend another Java class and implement multiple Java interfaces.
|
An interface can extend
another Java interface only.
|
|
An abstract class can be
extended using keyword extends
|
An interface class can be
implemented using keyword implements
|
|
A Java abstract class can
have class members like private, protected, etc.
|
Members of a
Java interface are public by default.
|
|
Example:
public abstract class Shape{
public abstract void draw();
}
|
Example:
public interface Drawable{
void draw();
}
|
115) Can we define private and protected modifiers for the members in interfaces?
No, they are implicitly public.
116) When can an object reference be cast to an interface reference?
An object reference can be cast to an interface reference when the
object implements the referenced interface.
117) How to make a read-only class in Java?
A class can be made read-only by making all of the fields private.
The read-only class will have only getter methods which return the private
property of the class to the main method. We cannot modify this property
because there is no setter method available in the class. Consider the
following example.
1.
2. public class Student{
3.
4. private String college="AKG";
5.
6. public String getCollege(){
7. return college;
8. }
9. }
118) How to make a write-only class in Java?
A class can be made write-only by making all of the fields private.
The write-only class will have only setter methods which set the value passed
from the main method to the private fields. We cannot read the properties of
the class because there is no getter method in this class. Consider the
following example.
1.
2. public class Student{
3.
4. private String college;
5.
6. public void setCollege(String college){
7. this.college=college;
8. }
9. }
119) What are the advantages of Encapsulation in Java?
There are the following advantages of Encapsulation in Java?
- By providing only the setter or getter method, you can make the class
read-only or write-only. In other words, you can skip the getter or setter
methods.
- It
provides you the control over the data. Suppose you want to set the value
of id which should be greater than 100 only, you can write the logic
inside the setter method. You can write the logic not to store the
negative numbers in the setter methods.
- It
is a way to achieve data hiding in Java because other class will not be
able to access the data through the private data members.
- The
encapsulate class is easy to test. So, it is better for unit testing.
- The
standard IDE's are providing the facility to generate the getters and
setters. So, it is easy and fast to create an encapsulated class in Java.
120) What is the
package?
A package is a group of similar type of classes, interfaces, and
sub-packages. It provides access protection and removes naming collision. The
packages in Java can be categorized into two forms, inbuilt package, and
user-defined package. There are many built-in packages such as Java, lang, awt,
javax, swing, net, io, util, sql, etc. Consider the following example to create
a package in Java.
1.
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
121) What are the
advantages of defining packages in Java?
By defining packages, we can avoid the name conflicts between the
same class names defined in different packages. Packages also enable the
developer to organize the similar classes more effectively. For example, one
can clearly understand that the classes present in java.io package are used to
perform io related operations.
122) How to create
packages in Java?
If you are using the programming IDEs like Eclipse, NetBeans,
MyEclipse, etc. click on file->new->project and
eclipse will ask you to enter the name of the package. It will create the
project package containing various directories such as src, etc. If you are
using an editor like notepad for java programming, use the following steps to
create the package.
- Define
a package package_name.
Create the class with the name class_name and
save this file with your_class_name.java.
- Now
compile the file by running the following command on the terminal.
1. javac -d . your_class_name.java
The above command creates the package with the name package_name in the
present working directory.
- Now,
run the class file by using the absolute class file name, like following.
1. java package_name.class_name
123) How can we
access some class in another class in Java?
There are two ways to access a class in another class.
- By
using the fully qualified name: To access a class in a
different package, either we must use the fully qualified name of that
class, or we must import the package containing that class.
- By
using the relative path, We can use the path of the class that is
related to the package that contains our class. It can be the same or
subpackage.
124) Do I need to
import java.lang package any time? Why?
No. It is by default loaded internally by the JVM.
125) Can I import
same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or the same class multiple times.
Neither compiler nor JVM complains about it. However, the JVM will internally
load the class only once no matter how many times you import the same class.
126) What is the
static import?
By static import, we can access the static members of a class
directly, and there is no to qualify it with the class name.
127) How many types of exception can occur in a
Java program?
There are mainly two types of exceptions: checked and unchecked.
Here, an error is considered as the unchecked exception. According to Oracle,
there are three types of exceptions:
- Checked
Exception: Checked
exceptions are the one which are checked at compile-time. For example,
SQLException, ClassNotFoundException, etc.
- Unchecked
Exception: Unchecked
exceptions are the one which are handled at runtime because they can not
be checked at compile-time. For example, ArithmaticException,
NullPointerException, ArrayIndexOutOfBoundsException, etc.
- Error: Error cause
the program to exit since they are not recoverable. For Example,
OutOfMemoryError, AssertionError, etc.
128) What is
Exception Handling?
Exception Handling is a mechanism that is used to handle runtime
errors. It is used primarily to handle checked exceptions. Exception handling
maintains the normal flow of the program. There are mainly two types of
exceptions: checked and unchecked. Here, the error is considered as the
unchecked exception.
129) Explain the
hierarchy of Java Exception classes?
The java.lang.Throwable class is the root class of Java Exception
hierarchy which is inherited by two subclasses: Exception and Error. A
hierarchy of Java Exception classes are given below:
130) What is the
difference between Checked Exception and Unchecked Exception?
1) Checked
Exception
The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions, e.g., IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked
Exception
The classes that extend RuntimeException are known as unchecked
exceptions, e.g., ArithmeticException, NullPointerException, etc. Unchecked
exceptions are not checked at compile-time.