0% found this document useful (0 votes)
163 views21 pages

Java Unit-1 Part-II Question and Answers

Ad hoc polymorphism, also known as method overloading, allows defining methods with the same name but different implementations based on argument types. Inheritance allows a child class to acquire properties of a parent class, providing code reuse. Access protection in Java includes public, private, protected, and default levels to control access to classes, fields, and methods from different relationships like the same class, subclass, or package.

Uploaded by

superfalcon
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
163 views21 pages

Java Unit-1 Part-II Question and Answers

Ad hoc polymorphism, also known as method overloading, allows defining methods with the same name but different implementations based on argument types. Inheritance allows a child class to acquire properties of a parent class, providing code reuse. Access protection in Java includes public, private, protected, and default levels to control access to classes, fields, and methods from different relationships like the same class, subclass, or package.

Uploaded by

superfalcon
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 21

1. What is meant by ad-hoc polymorphism?

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.

2. What is inheritance? Give example


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.
.

The inheritance can be defined as follows.


The inheritance is the process of acquiring the properties of one class to another class.

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 {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.setData(100);
obj.showData();

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.
.

The inheritance can be defined as follows.


The inheritance is the process of acquiring the properties of one class to another
class.
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.

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.

How to prevent a class from inheritance


While one of Java's strengths is the concept of inheritance, in which one class can derive
from another, sometimes it's desirable to prevent inheritance by another class. To prevent
inheritance, use the keyword "final" when creating the class.
For example, if a class is likely to be used by other programmers, you may wish to
prevent inheritance if any subclasses created could cause problems. A typical example is
the String class. If we wanted to create a String subclass:

public class MyString extends String{

We would be faced with this error:


cannot inherit from final java.lang.String
The designers of the String class realized that it was not a candidate for inheritance and
have prevented it from being extended.
4. Describe different levels of access protection available in java?
Any two different Java objects have one of four relations to each other. The four
relations are:

 The objects are in the same class.


 One object is a subclass of the other object's class.
 The objects are in the same package.
 None of the above. (Both objects are members of the general public.)
These relationships are not mutually exclusive. One object can be a subclass of another object in
the same package, for example.

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.

Access Protection Example

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.

This is Protection.java file:

package pkg1;
public class Protection

int n = 1;

private int n_priv = 2;

protected int n_prot = 3;

public int n_publ = 4;

public Protection()

System.out.println("base constructor");

System.out.println("n = " + n);

System.out.println("n_priv = " + n_priv);

System.out.println("n_prot = " + n_prot);

System.out.println("n_publ = " + n_publ);

This is Derived.java file:

package pkg1;

class Derived extends Protection


{

Derived()

System.out.println("derived constructor");

System.out.println("n = " + n);

/* class only

* System.out.println("n_priv = "4 + n_priv); */

System.out.println("n_prot = " + n_prot);

System.out.println("n_publ = " +n_publ);

This is SamePackage.java file:

package pkg1;

class SamePackage

SamePackage()

Protection pro = new Protection();


System.out.println("same package constructor");

System.out.println("n = " + pro.n);

/* class only

* System.out.println("n_priv = " + pro.n_priv); */

System.out.println("n_prot = " + pro.n_prot);

System.out.println("n_publ = " + pro.n_publ);

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.

This is Protection2.java file:

package pkg2;

class Protection2 extends pkg1.Protection

Protection2()

System.out.println("derived other package constructor");


/* class or package only

* System.out.println("n = " + n); */

/* class only

* System.out.println("n_priv = " + n_priv); */

System.out.println("n_prot = " + n_prot);

System.out.println("n_publ = " + n_publ);

This is OtherPackage.java file:

package pkg2;

class OtherPackage

OtherPackage()

pkg1.Protection pro = new pkg1.Protection();

System.out.println("other package constructor");


/* class or package only

* System.out.println("n = " + pro.n); */

/* class only

* System.out.println("n_priv = " + pro.n_priv); */

/* class, subclass or package only

* System.out.println("n_prot = " + pro.n_prot); */

System.out.println("n_publ = " + pro.n_publ);

If you want to try these two packages, here are two test files you can use.

The one for package pkg1 is shown here:

/* demo package pkg1 */

package pkg1;

/* instantiate the various classes in pkg1 */


public class Demo

public static void main(String args[])

Protection obj1 = new Protection();

Derived obj2 = new Derived();

SamePackage obj3 = new SamePackage();

The test file for pkg2 is shown below :

/* demo package pkg2 */

package pkg2;

/* instantiate the various classes in pkg2 */

public class Demo

public static void main(String args[])

Protection2 obj1 = new Protection2();

OtherPackage obj2 = new OtherPackage();


}

5. How does polymorphism promote extensibility? Explain with example

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 in Java Leverages Extensibility

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

Figure 1: A shape hierarchy chart

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;

isoTri=new Triangle(); // Not OK...


A superclass reference variable can refer to a subclass object, but a subclass reference
variable cannot refer to a superclass object (unless explicitly casted, which we shall later
down the line).

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();

// area() method defined in the Triangle class

s1.area();

s1=new Rectangle();

// area() method defined in the Rectangle class

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.

This commitment is referred to as binding a method invocation to a method definition.


Although in other situations, this binding of a method invocation to a method definition
can occur at compile time, in polymorphic reference this decision of binding is not
possible until runtime. The method definition to use is based on the object referred to by
the reference variable at that particular moment. The following example will clarify the
idea.
Shape s1;

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.

6. What is polymorphism ? Explain different types of polymorphism with examples?

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.

An important example of polymorphism is how a parent class refers to a child class


object. In fact, any object that satisfies more than one IS-A relationship is polymorphic
in nature.
For instance, let’s consider a class Animal and let Cat be a subclass of Animal. So, any
cat IS animal. Here, Cat satisfies the IS-A relationship for its own type as well as its
super class Animal.

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;
}

public int add(int x, int y, int z){ //method 2


return x+y+z;
}

public int add(double x, int y){ //method 3


return (int)x+y;
}

public int add(int x, double y){ //method 4


return x+(int)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.

Have a look at the following example.

class Vehicle{
public void move(){
System.out.println(“Vehicles can move!!”);
}
}

class MotorBike extends Vehicle{


public void move(){
System.out.println(“MotorBike can move and accelerate too!!”);
}
}

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.

7. Write a program to demonstrate hierarchical and multiple inheritance using interfaces?

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 Vehicle implements vehicleone,vehicletwo{


public void distance(){
int distance=speed*100;
System.out.println("distance travelled is "+distance);
}
public void speed(){
int speed=distance/100;
}
}

class MultipleInheritanceUsingInterface{
public static void main(String args[]){
System.out.println("Vehicle");
obj.distance();
obj.speed();
}
}
Sample Output
Output is:
distance travelled is 9000

You might also like