Java Unit-1 Part-II Question and Answers
Java Unit-1 Part-II Question and Answers
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc
polymorphism carried out with a method overloading concept.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded
with the respective overloaded method based on the arguments.
The ad hoc polymorphism implemented within the class only.
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.
The Parent class is the class which provides features to another class. The parent class is also
known as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also
known as the Derived Class or Subclass.
Example:
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
System.out.println("Value of a is " + a);
}
}
public class SingleInheritance {
3. Define inheritance. What are the benefits of inheritance? What costs are associated with
inheritance? How to prevent a class from inheritance?
The inheritance is a very useful and powerful concept of object-oriented programming. In
java, using the inheritance concept, we can use the existing features of one class in
another class. The inheritance provides a greate advantage called code re-usability. With
the help of code re-usability, the commonly used code in an application
need not be written again and again.
.
Benefits of Inheritance
Inheritance helps in code reuse. The child class may use the code defined in the parent
class without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class.
An inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered
by the derived class.
Costs of Inheritance
Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This
means one cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.
You can define which of your class's members, that is its fields and its methods, are accessible to
other objects in each of these four groups, relative to the current class.
If you want any object at all to be able to call a method or change a field, declare it public.
If you want only objects in the same class to be able to get or set the value of a field or invoke a
method, declare it private.
If you want access restricted to subclasses and members of the same package, declare
it protected.
Finally, to restrict access only to objects in the same package, use no access declaration at all.
This is called "package" or "default" access, but it has no keyword. The default keyword means
something else entirely.
By default, all classes you write are in the same package. However, they are in different
packages from the Java classes like System or Applet.
The public fields and methods of an object can be accessed from anywhere the object itself can
be seen. Anyone can touch an object's public members. They should be kept to a minimum.
Public fields should relate very closely to the core functionality of the class. They should not
show intimate details of the inner workings of the class. Except in very simple instances fields
should probably not be public.
The private fields and methods of an object can only be accessed by the object itself and by other
objects of the same class (siblings). An object may touch its sibling's private parts. A sibling is
an object in the same class but which is not the same object.
Here the upcoming example allows all the combinations of access control modifiers. This
example has two packages and five classes.
Always remember that the classes for the two different packages need to be stored in directories
after their respective packages (in this case pkg1 and pkg2).
The source for the first package defines the three classes i.e., Protection, Derived, and
SamePackage. The first class defines the four variables of type int in each of the legal protection
modes. The variable n declared with the default protection, the variables n_priv, n_prot, and
n_publ is private, protected, and public respectively.
Each subsequent class in the following example will try to access the variables in an instance of
this class. The lines that will not compile due to the access restrictions are commented out.
Before each of these lines is a comment that listing the places from which this level of protection
would allow access.
The second class named Derived, is a subclass of Protection in the same package, pkg1. This
grants Derived access to every variable in the class Protection except for n_priv, the private one.
The third class named SamePackage, is not a subclass of the class Protection, but is in the same
package and also has access to all but not n_priv.
package pkg1;
public class Protection
int n = 1;
public Protection()
System.out.println("base constructor");
package pkg1;
Derived()
System.out.println("derived constructor");
/* class only
package pkg1;
class SamePackage
SamePackage()
/* class only
Following is the source code for the other package named pkg2. The two classes defined in the
package pkg2 cover the outer two conditions that are affected by the access control. The first
class named Protection2, is a subclass of pkg1.Protection. This grants access to all of pkg1.
Variables of the class Protection except for n_priv (because it is private) and n, the variable
declared with the default protection.
Always remember that the default only allows access from within the class or the package, not
extra-package subclasses. Finally, the class OtherPackage has access to n_publ only which was
declared as public.
package pkg2;
Protection2()
/* class only
package pkg2;
class OtherPackage
OtherPackage()
/* class only
If you want to try these two packages, here are two test files you can use.
package pkg1;
package pkg2;
Polymorphism in Java is closely associated with the principle of inheritance. The term
“polymorphic” means “having multiple forms.” Polymorphism in Java simplifies
programming by providing a single interface overlaid with multiple meanings as it goes
through the rigor of subclassing. This article is a attempt to explore the concept with a
focus on Java with appropriate illustrations and examples.
Polymorphism leverages extensibility. That means we can assign new classes with almost
no modification of the existing code, provided the class is part of the inheritance
hierarchy. The new class becomes part of the classification, like a Lego attached to a
construction in such a manner that the construction would not crumble even if we detach
one. As per the norms of inheritance, a new class acquires the property and methods of
the superclass and is open to override only those methods that it is interested in
modifying. Other derived implementation may be used as it is implemented by the
superclass without making any changes.
For example, a Shape class contains a method called area(). Now, if we extend this class
to create a Rectangle class (the area formula is quite different from a triangle; had we
created a class called Triangle), we need to write only the Rectangle class and part of the
code that instantiates the Rectangle object. However, the Rectangle has the option to use
the generic implementation of the area() method defined by its superclass; otherwise, we
can modify it to meet our specific needs. So, polymorphism in Java is in a way to enable
us to create a class in general, which becomes more specific as we extend it through sub-
classification.
Dynamic Binding
Typically, the type of the reference variable exactly matches with the class object that it
refers to. This, however, is not always the case with polymorphism. For example,
Poly1
Triangle triangle;
The triangle is a reference to the Triangle class object; it can be equally used to refer to
the object of IsocelesTriangle. The variable type and the object it refers to must be
compatible, but their types need not be the same. This is called polymorphic reference. A
polymorphic reference can refer to different objects at different points of time. We
always can create a reference to the topmost class object in the inheritance hierarchy,
such as,
Shape s1;
s1=new Triangle(); // OK
IsocelesTriangle isoTri;
Suppose there is an abstract method called area() declared in the abstract Shape class.
This means that every subclass must provide the implementation of that method. So, the
call to the area() method must be different under different circumstances.
Shape s1;
s1=new Triangle();
s1.area();
s1=new Rectangle();
s1.area();
The specific area() method invoked through the reference variable depends on the
reference to the object it holds at a certain point in time. In the preceding example, when
the variable s1 holds the reference to the Triangle class object, an invocation to area()
will call the implementation defined in the Triangle class. And, when s1 refers to the
Rectangle class object, the invocation to area() methods invokes the area() method
defined in the Rectangle class.
double result;
if(choice==0)
s1=new Triangle();
else
s1=new Rectangle();
result=s1.area();
Observe that the binding of invocation to the area() method to the implementation
defined in Rectangle or Triangle can only be decided upon the value of the choice
variable checked conditionally by the if statement. The invocation to area() being
bounded to the definition of Rectangle or Triangle is equally probable. The decision can
only be ascertained at runtime.
This is referred to as late binding or dynamic binding. Dynamic binding is obviously less
efficient than static binding or binding at compile time, yet the overhead is more
acceptable in view of flexibility.
The word ‘polymorphism’ literally means ‘a state of having many shapes’ or ‘the
capacity to take on different forms’. When applied to object-oriented programming
languages like Java, it describes a language’s ability to process objects of various types
and classes through a single, uniform interface.
Polymorphism in Java has two types: Compile time polymorphism (static binding) and
Runtime polymorphism (dynamic binding). Method overloading is an example of static
polymorphism, while method overriding is an example of dynamic polymorphism.
Note: It’s also legal to say every object in Java is polymorphic in nature, as each one
passes an IS-A test for itself and also for Object class.
Static Polymorphism:
In Java, static polymorphism is achieved through method overloading. Method
overloading means there are several methods present in a class having the same name but
different types/order/number of parameters.
At compile time, Java knows which method to invoke by checking the method signatures.
So, this is called compile time polymorphism or static binding. The concept will be clear
from the following example:
class DemoOverload{
public int add(int x, int y){ //method 1
return x+y;
}
class Test{
public static void main(String[] args){
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3)); //method 1 called
System.out.println(demo.add(2,3,4)); //method 2 called
System.out.println(demo.add(2,3.4)); //method 4 called
System.out.println(demo.add(2.5,3)); //method 3 called
}
}
In the above example, there are four versions of add methods. The first method takes two
parameters while the second one takes three. For the third and fourth methods, there is a
change of order of parameters. The compiler looks at the method signature and decides
which method to invoke for a particular method call at compile time.
Dynamic Polymorphism:
Suppose a subclass overrides a particular method of the superclass. Let’s say we create an
object of the subclass and assign it to the superclass reference. Now, if we call the
overridden method on the superclass reference then the subclass version of the method
will be called.
class Vehicle{
public void move(){
System.out.println(“Vehicles can move!!”);
}
}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move(); // prints MotorBike can move and accelerate too!!
vh=new Vehicle();
vh.move(); // prints Vehicles can move!!
}
}
It should be noted that in the first call to move(), the reference type is Vehicle and the
object being referenced is MotorBike. So, when a call to move() is made, Java waits until
runtime to determine which object is actually being pointed to by the reference. In this
case, the object is of the class MotorBike. So, the move() method of MotorBike class will
be called. In the second call to move(), the object is of the class Vehicle. So, the move()
method of Vehicle will be called.
As the method to call is determined at runtime, this is called dynamic binding or late
binding.
Inheritance is when an object or class is based on another object or class, using the same
implementation specifying implementation to maintain the same behavior. It is a
mechanism for code reuse and to allow independent extensions of the original software
via public classes and interfaces. The relationships of objects or classes through
inheritance give rise to a hierarchy. Multiple Inheritance allows a class to have more than
one super class and to inherit features from all parent class. it is achieved using interface.
Syntax:
public interface A{
//Do Something
}
public interface B extends A{
//Do Something
}
public interface C extends A{
//Do Something
}
Multiple Inheritance Using Interface Example Program
interface vehicleone{
int speed=90;
public void distance();
}
interface vehicletwo{
int distance=100;
public void speed();
}
class MultipleInheritanceUsingInterface{
public static void main(String args[]){
System.out.println("Vehicle");
obj.distance();
obj.speed();
}
}
Sample Output
Output is:
distance travelled is 9000