Sie sind auf Seite 1von 48

CHAPTER-INTRODUCTION TO JAVA

LONG AND SHORT TYPE QUESTIONS

Q1. Explain public static void main(String args[]).


Ans:-The line
public static void main(String args[])
defines a method named main.Conceptually, this is similar to the main()function in C/C++.
Every java program must include the main()method. This is the starting point for the interpreter
to begin the execution of the program. A java application can have any number of classes but
only one of them must include a main method to initiate the execution. Java applets will not use
the main method at all.
This line contains a number of keywords, public, static and void.
All parameters to a method are declared inside a pair of parenthesis. Here, String args[] declares
a parameter named args, which contain an array of objects of the class type String.

Q2. What do you mean by garbage collection in java?


Ans:-The user need not allocate or deallocate the memory in Java. Everything will be taken care
of by JVM only. JVM will allocate the necessary memory needed by a Java program. JVM is
Public Static Void
The keyword public is an Next appears the keyword The type modifier void states
access specifier that declares static, which declares this that the main method does not
the main method as method as one that belongs to return any value (but simply
unprotected and therefore the entire class and not a part prints some text to the screen.)
making it accessible to all of any object of the class. The
other classes. main must always declared as
staticsince the interpreter uses
this method before any object
are created.
also capable of deallocating the memory when it is not used. Garbage collector is a form of
memory management that checks the memory from time to time and marks the variables or
objects not used by the program, automatically. After repeatedly identifying the same variable or
object, garbage collector confirms that the variable or object is not used and hence can be
deleted. The technique is called garbage collection.

Q3. What is byte-code?


Ans:-Java byte-code is the instruction set of the Java virtual machine. Each bytecode is
composed of one, or in some cases two bytes that represent the instruction (opcode), along with
zero or more bytes for passing parameters.
The Java bytecode system does not directly support floating point operations
beyond 32 bits, except indirectly via bytecodes that enable use of 64-bit and 80-bit intermediate
IEEE floating point operations.
Q4. What does JVM do?
Ans:- A Java Virtual Machine (JVM)is a simulated computer within the computer and does all
major functions of a real computer. JVM is responsible for taking the .class file and converting
each byte code instruction into the machine language instruction that can be executed by the
microprocessor. In JVM, there is a module (or program) called class loader sub system, which
performs the following functions:
 First of all, it loads the .class file into memory.
 Then it verifies whether all byte-code instructions are proper or not. If it finds any
instruction suspicious, the execution is rejected immediately.
 If the byte instructions are proper, then it allocates necessary memory to execute the
program.

Q5. Why java is called compiled –interpreted language?


Ans:- Usually a computer language is either compiled or interpreted. Java combines both these
approaches thus making Java a two-stage system. First, Java compiler translates source code into
what is known as byte-code instructions. Byte codes are not machine instructions and therefore,
in the second stage, Java interpreter generates machine code that can be directly executed by the
machine that is running the Java program. We can thus say that Java is both a compiled and an
interpreted language.

Q6. Why Java is called robust language?


Ans:- Java is a robust language. It provides many safeguards to ensure reliable code. It has strict
compile time and run time checking for data types. It is designed as a garbage –collected
language relieving the programmers virtually all memory management problems. Java also
incorporates the concept of exception handling which captures series errors and eliminates any
risk of crashing the system
CLASS & OBJECTS

Multiple Choice Questions & Answers

1) Examine the following class definitions to detect errors, if any abstract


class1{abstract void func1(float x, float y) {} }
a) Class header definition is wrong
b) Method definition is wrong
c) Constructor needs to be defined
d) No errors
2) All classes in java are the sub-class of
a) Final class b) Object class c) Static class d) Super class
3) The qualifier is a part of the
a) Class b) association class c) association path d) none of these
4) What is the error in the following code?
class Test
{
abstract void display();
}
a) No error
b) Method display () should be declared as static
c) Test class should be declared as abstract
d) Test class should be declared as public
5) In which class is the wait () method defined?
a) Applet b) Runnable c) Thread d) Object
6) Which of the following keywords are used to control access to a class Member?

a) default b) abstract c) public d) interface


8) Which statement about static inner classes is true?
a) Static inner classes may access any of the enclosing classes’ members
b) Static inner classes may have only static methods
c) Static inner classes may not be instantiated outside of the enclosing
class
d) Static inner classes do not have a reference to the enclosing class
10) Under what situations do you obtain a default constructor?
a) when you define any class
b) when the class has no other constructor
c) when you define at least one constructor
d) None of these
11) The use of protected keyword to a member in a class will restrict its
Visibility as
a) Visible only in the class and its subclass in the same package
b) Visible only inside the same package
c) Visible in all classes in the same package and subclasses in other package
d) None of these
12) Which of the following is a wrapper class?
a) Byte b) Random c) Vector d) String
13) A constructor can be inherited using the keyword
a) Final b) Static c) super d) None of these
14) How many default constructors can a class have, when it has
constructor?
a) 1 b) 0 c) 2 d) Any number
15) Which one of the following statements is wrong?
a) A base class reference can refer to an object of a derived class
b) The dynamic method dispatch is not carried out at the run time
c) The super () construct refers to the base class constructor
d) The super.base-class-method-name() format can be used only within a
derived class
17) If a data-item is declared as a protected access specifier then it can be
accessed:
a) Anywhere in the program b) By the base and derived classes
c) Only by base d) Only by derived classes

Long Answer Type Question


1) What is object & class ?
Ans: Object is the basic runtime entities in an object-oriented system. Object oriented
programming allows us to decompose a problem into a number of entities called objects. The
combination of data and methods make up an object. The data of an object can be accessed only
by the methods associated with that object. Objects may communicate with each other through
methods.
A class is a model for creating objects .Classes are user -defined data types and behave like the
built-in types of a programming language. Once a class has been defined we can create any
number of objects belonging to that class.

2) What is constructor?
Ans: Java supports a special type of method called a constructor that enables an object to
initialize itself when it is created. Constructors have the same name as the class itself. They do
not specify a return type not even void. This is because they return the instance of the class itself.
Example:-
class A
{
int x,y;
A(int a,int b)
{
a=x;
b=y;
}
void add()
{
int s;
s=x+y;
System.out.println("the sum is="+s);
}
}
class Z
{
public static void main(String a[])
{
A obj=new A(4,5);
obj.add();
}
}
Output:-

3) What are the properties of the constructor?


Ans:properties:-
a.The constructor name and class name have the same name and the constructor’s name should
end with a pair of simple braces.
b. A constructor may have or may not have parameters.
c. A constructor does not return any value not even ‘void’. If a method does not return any value
we write ‘void’ before the method name.
d. A constructor is automatically called and executed at the time of creating an object.
e. A constructor is called and executed only once per object. This means when we create an
object the constructor is called. When we create second object again the constructor is called
second time.

4) Explain what is overloaded constructor with the help of example.


Ans: Writing two or more constructor with the same name but with difference in the parameters
is called constructor overloading. Such constructors are useful to perform different tasks.
Example:-
class A
{
int a, b;
A()
{
System.out.println("IT");
}
A(int x)
{
a=b=x;
}
A(int x, int y)
{
a=x;
b=y;
}
void add()
{
int s;
s=a+b;
System.out.println("Sum="+s);
}
}
class B
{
public static void main(String a[])
{
A ob1=new A();
A ob2=new A(7);
A ob3=new A(5,10);
ob1.add();
ob2.add();
ob3.add();
}
}
Output:

5) What are the different type of constructor explain with example?


Ans: There are two types of constructor:
1) Default constructor
2) Parameterized constructor

Default Constructor Parameterized Constructor

1.Default constructor is useful to 1. Parameterized constructor is


initialize all objects with same useful to initialize each object with
data. different data.

2.Default constructor does not have 2.Parameterized constructor will


any parameters. have 1 or more parameters.

3.When data is not passed at the 3.When data is passed at the time of
time of creating an object. Default creating an object .Parameterized
constructor is called. constructor is called.

Example: Default constructor


class A
{
A()
{
System.out.println("IT");
}
public static void main(String a[])
{
A ob=new A();
}
}

Output:-

Parameterized constructor :
class A
{
int a,b
A(int x,int y)
{
a=x;
b=y;
}
int add()
{
int; z;
z=a+b;
return(z);
}
}
class B
{
public static void main(String a[])
{
A ob=new A(10,20);
int p=ob.add();
System.out.println("Sum="+p);
}
}
Output:

6) What do you mean by variable hiding?

Ans: In Java, there are three kinds of variables: local variables, instance variables, and class
variables. Variables have their scopes. Different kinds of variables have different scopes.
 A local variable hides an instance variable inside the method block.
 When an instance variable in a subclass has the same name as an instance variable of its
super class, then instance variable of the sub class hide the inherited version of the
instance variable having same name.

7) What is the use of “this” keyword?


Ans: ‘this’ is a keyword that refers to the object of the class where it is used. Generally, we write
instance variables, constructors and methods in a class. All these members are referenced by
‘this’.
Now we take one example:
// this - refers to all the members of present class
class Sample
{
int x; // x is instance variable
Sample()
{
this(10); //call present class parameterized constructor and pass 10
this.access(); //call present class method
}
Sample(int x)
{
this.x=x; // refer present class instance variable
}
void access()
{
System.out.println("x="+x);
}
}
class B
{
public static void main(String arg[])
{
Sample ob=new Sample();
}
}

Output:

8) What is method overloading? Explain with an example.


Ans: writing two or more methods in the same class in such way that each method has same
name but different parameter is called method overloading. Method overloading is used when
objects are required to perform similar tasks but using different input parameters. When we call a
method in an object, Java matches up the method name first and then the number and type of
parameters to decide which one of the definitions to execute.
class A
{
int a,b
void add()
{
int c=a+b;
System.out.println("sum="+c);
}
void add(int x,int y)
{
int z;
z=x+y;
System.out.println("sum="+z);
}
void add(int p)
{
int q=p+p;
System.out.println("sum="+q);
}
}
class B
{
public static void main(String a[])
{
A ob=new A();
ob.a=5,ob.b=6;
ob.add();
ob.add(6,7);
ob.add(8);
}
}
OUTPUT:

9) What is the difference between normal method and constructor?


Ans:-
Constructor Method
A constructor is used to initialize the instance A method is used for any general purpose
variables of class. processing or calculations.
A constructor’s name and class name should be A method’s name and class name can be same
same. or different.
A constructor is called at the time of creating A method can be called after creating the
the object. object.
A constructor is called only once per object. A method can be called several times on the
object.
A constructor is called and executed A method is executed only when we call it.
automatically.

10) What does it mean that a method or field is “static”?


Ans: A static method or a static variable is declared by using the keyword ‘static’.
 A static variable will have only one copy in memory and that is shared by all the objects.
static int x;
 static method is a method that does not act upon instance variables of a class. Static
method can access only static variables. Because the JVM first executes the static
methods and then only it creates the objects. Since the objects are not available at the
time of calling the static methods, the instance variables are not available. Static methods
are called using Classname.methodname().
Example : static method trying to access instance variable
class A
{
int x;
A(int a)
{
x=a;
}
static void show()
{
System.out.println("x="+x);
}
}
class B
{
public static void main(String arg[])
{
A ob=new A(5);
A.show();

}
}

Output:

Example : static method trying to access static variable


class A
{
static int x;
static void show()
{
System.out.println("x="+x);
}
}
class B
{
public static void main(String arg[])
{
A.x=5;
A.show();

}
}

Output:

11) Describe the following with suitable example-


a) Polymorphism b) Encapsulation.

a) POLYMORPHISM:
Polymorphism is an important Object Oriented Programming concept. Polymorphism means the
ability to take more than one form. For example, an operation may exhibit different behavior in
different instances. The behavior depends upon the types of data used in the operation.
Polymorphism plays an important role in allowing objects having different internal structures to
share the same external interface.
EXAMPLE OF POLYMORPHISM:-
class A
{
int a,b
void add()
{
int c=a+b;
System.out.println("sum="+c);
}
void add(int x,int y)
{
int z;
z=x+y;
System.out.println("sum="+z);
}
void add(int p)
{
int q=p+p;
System.out.println("sum="+q);
}
}
class B
{
public static void main(String a[])
{
A ob=new A();
ob.a=5,ob.b=6;
ob.add();
ob.add(6,7);
ob.add(8);
}
}
Output:-

b) ENCAPSULATION:
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the
data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden
from other classes, and can be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.

EXAMPLE OF ENCAPSULATION:
This will produce the following result –
Output:-
12) What is static block?
Ans:-
A static block is a block of statements declared as ‘static’, some thing like this
static {
Statements;
}
JVM executes a static block on a highest priority basis. This means JVM first goes to a static
block even before it looks for the main() method in the program. This can be understood from
program

Output:

13) What is nesting of method?


Ans:-
When a method in java calls another method in the same class, it is called Nesting of method.
Output:

14) What is call by value technique for method calling?


Ans:- Call by value approach copies the value of an argument into the formal parameter of the
subroutine. Therefore, changes made to the parameter of the subroutine has no effect on the
argument. Although Java uses call-by-value to pass all arguments, the precise effect differs
between whether a primitive type or a reference type is passed.
When you pass a primitive type to method, it is passed by value. Thus, a copy of the argument is
made, and what occurs to the parameter that receives the argument has no effect outside the
method .For example consider the following program:
Output:

15) What is call by reference technique for method calling?


Ans: Call-by-reference approach to an argument (not the value of the argument ) is passed to the
parameter. Inside the subroutine, this reference is used to access the actual argument specified in
the call. This means that changes made to the parameter will affect the argument used to call the
subroutine .
16) Explain methods returning object with a example?
Ans:- A method can return any type of data ,including class types that you create.
For example, in the following program, the incrByTen() method returns an object in which the
value of a is ten greater than it is in the invoking object.
As you can see, each time incrByTen() is invoked, a new object is created, and a reference to it
is returned to the calling routine.
17) Compare object and object reference?
Ans:
Object – Object refers to a particular instance of a class in memory. Objects in java are created
using the ‘new’ keyword.
Object reference – Object reference is a unique identification number allocated to the objects by
the JVM. This reference number is created based on the location of the object in memory. The
reference number is also called hash code number.
To know the reference (or hash code) of an object, we can use hashCode() method of Object
class.
Suppose ‘A’ is a class, then
A ob=new A(); // ob is reference of object of class A.
System.out.println(ob.hashCode()); // displays hash code stored in ‘ob’.

INTERVIEW QUESTION
1) What is object oriented approach?
Object oriented programming approach is a programming methodology to design computer
programs using classes and objects.
2) What is the difference between a class and an object?
A class is model for creating objects and does not exist physically. An object is any thing that
exists physically both the class and objects contain variables and methods.
3) What is the difference between object oriented programming languages and object based
programming languages?
Object oriented programming languages follow all the features of Object Oriented Programming
System (OOPS). Smalltalk, Simula-67, C++, Java are examples for OOPS languages.
Object based programming languages follow all the features of OOPS, except Inheritance. For
example, JavaScript and VBScript will come under object based programming languages.
4) What is hash code?
Hash code is a unique identification number allotted to the objects by the JVM. This hash code
number is also called reference number which is created based on the location of the object in
memory and is unique for all objects except for String objects.
5) How can you find the hash code of an object?
The hashCode() method of 'Object' class in Java.lang package is useful to find the hash code of
an object.
6) Can you declare a class as 'private'?
No, if we declare a class as private then it is not available to Java compiler and hence a compile
time error occurs. But inner classes can be declared as private.
7) When is a constructor called, before or after creating the object?
A constructor is called concurrently when the object creation is going on. JVM first allocates
memory for the object and then executes the constructor to initialize the instance variable. By the
time object creation is completed the constructor execution is also completed.
8) What is the difference between default constructor and parameterized constructor ?
Default constructor Parameterized constructor
Default constructor is useful to initialize all Parameterized constructor is useful to initialize
objects with same data. each object with different data.
Default constructor does not have any Parameterized constructor will hava 1 or more
parameters. parameters.
When data is not passed at the time of creating When data is not passed at the time of creating
an object, default constructor is called an object, Parameterized constructor is called.

9) What is the difference between a constructor and a method?


Constructor Method
A constructor is used to initialize the instance A method is used for any general purpose
variables of class. processing or calculations.
A constructor’s name and class name should be A method’s name and class name can be same
same. or different.
A constructor is called at the time of creating A method can be called after creating the
the object. object.
A constructor is called only once per object. A method can be called several times on the
object.
A constructor is called and executed A method is executed only when we call it.
automatically.

10) What is constructor overloading?


Writing two or more constructors with the same name but with difference in the parameters is
called constructor overloading. Such constructors are useful to perform different tasks.
11) What are instance methods?
Instance methods are the methods which act on the instance variables of the class. To call the
instance methods, we should use the form objectname.methodname ()
12) What are static methods?
Static methods are the methods which do not act upon the instance variables of a class. Static
methods are declared as 'static'.
13) What is the difference between instance variables and class variables (static variables)?
1. An instance variable is a variable whose separate copy is available to each object. A class
variable is a variable whose single copy in memory is shared by all objects.
2. Instance variables are created in the objects on heap memory. Class variables are stored on
method area
14) Why instance variables are not available to static methods?
After executing static methods, JVM creates the objects: So the instance variables of the objects
are not available to static method.
15) Is it possible to compile and run a Java program without writing main () method?
Yes, it is possible by using a static block in the Java program.
16)How are objects are passed to methods in Java?
Primitive data types, objects, even object references-every thing is passed to methods using 'pass
by value' or 'call by value' concept. This means their bit by bit copy is passed to the methods
17) What are factory methods?
A factory method is a method that creates and returns an object to the class to which it belongs.
A single factory method replaces several constructors in the class by accepting different options
from the user, while creating the object.
18) What is object graph?
Object graph is a graph showing relationship between different objects in memory.
19) What is anonymous inner class?
It is an inner class whose name is not written in the outer class and for which only one object is
created.
INHERITANCE
MULTIPLE CHOICE QUESTIONS
Q1. Exception is defined in...............package.
a) java.util b) java.lang c) java.awt d)java.jo
Q2. Which of the options matches the following line.
The scheme for representing the relationships between classes
a)Method b) inheritance c) message d) polymorphism
Q3.Which of the following statements are incorrect?
a) public members of class can be accessed by any code in the program.
b) private members of class can only be accessed by other members of the class.
c) private members of class can be inherited by a sub class, and become protected members
in sub class.
d) protected members of a class can be inherited by a sub class, and become private members of
the sub class.
Q4.The method int func (int i,int j){ } can be overloaded using
a) int func (int i,intj,int k){ } b) int func (float i,float j){ }
c) float func (int i,int j){ } d)int func (int a,int b ){ }
e) float func (inti,intj,float k){ }
a) (b)&(c) b) (c)&(d) c) (a),(b),(c)&(e) d) (a),(b)& (e)
Q5. To inherit interface in a class, we use the keyword
a) extends b) implements c) both (a) and (b) d)none of these
Q6. If a base class has a method defined as abstract void method(); which of the following
lines is mandatory in the derived lines?
a)void method(){} b)int method() {return(0);}
c)void method (inti){} d)private void method(){}

Q7. Which of these keyword can be used in subclass to call the constructor of superclass?

a) super b) this c) extent d) extends

Q8. What is the process of defining a method in subclass having same name & type
signature as a method in its super class?
a) Method overloading b) Method overriding

c) Method hiding d) None of the mentioned

LONG AND SHORT TYPE QUESTIONS

Q1)What is inheritance?
Ans: Deriving new classes from existing classes such that the new classes acquire all the features
of existing classes is called inheritance.
All the members of a class and use them in another class by relating objects of the two classes.
This is possible by using inheritance concept.
Using inheritance, create a general class that defines traits common to a set of related items. This
class can then be inherited by other, more specific classes, each adding those things that are
unique to it. In the terminology of Java, a class that is inherited is called a super class. The class
that does the inheriting is called a sub class. Therefore, a subclass is a specialized version of a
super class. It inherits all of the instance variables and methods defined by the super class and
add its own, unique elements. To inherit a class, simply incorporate the definition of one class
into another by using the extends keyword.
Example:
Class A//super class
{
Void dispalyname()//method of super class
{System.out.println(“NAME”);}
}
Class B extends class A//sub class
{
Void displayclgname()//method of sub class
{System.out.println(“AEC”);}
}
Class C//main class
{
Public static void main(String S[ ])
{
B ob2=new B();
ob2.displayname();
ob2.displayclgname();}
}
}

OUTPUT:
D:\javaprgm>java C
NAME
AEC

Q2) What are the different type of inheritance supported by Java?


Ans:Inheritance are 4 types:
1.Single level Inheritance
2.Hierarchical Inheritance
3.Multi Level Inheritance

INHERITANCE:-
Deriving new classes from existing classes such that the new classes acquire all the features of
existing classes is called inheritance.
Inheritance

Single Level Inheritance Multi Level Hierarchical


Inheritance Inheritance

One another type of inheritance, is Multiple inheritance which is not supported by java.
SINGLE LEVEL INHERITANCE:-
Producing a sub class from a single super class is called single level inheritance.

EMPLOYEE

Class employee
Extends
Department DEPARTMENT

MULTI LEVEL INHERITANCE:-


Inheritance is the process of inheriting properties of objects of one class by objects of another
class. When a class is derived from a class which is also derived from another class, i.e. a parent
class having a subclass which further has another subclass, such inheritance is called Multilevel
Inheritance.
A

HIRERCHICAL INHERITANCE:-
Inheritance is the process of inheriting properties of objects of one class by objects of another
class. When more than one class is derived from a single base class, such inheritance is known as
hierarchical inheritance.
A

B C D

EXAMPLE OF INHERITANCE:-
Q3)What is Method overriding?
Ans: In a class hierarchy, when a method in a subclass has the same name and same type
signature as a method in its super class, then the method in the subclass is said to override the
method in the super class. When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass. The version of the method
defined by the super class will be hidden

Example:
Q4) Difference between method overriding and method overloading?

Ans:
Method Overloading Method Overriding
Writing two or more methods with the same Writing two or more methods with same
name with different signatures is called name and same signatures is called method
method overloading overriding
Method overloading is done in the same Method overriding is done in super classes
class.
In method overloading method return type In method overriding method return type
can be same or different should also be same
JVM decides which method is called JVM decides which method is called
depending on the difference in the method depending on data type of the object used to
signatures call the method
Method overloading is done when the Method overriding is done when the
programmer wants to extend the already programmer wants to provide a different
available feature implementation for the same feature
Method overloading is code refinement. Method overriding is code replacement. The
Same method is refined to perform a class method overwrites the super class
different task method.

Q5)Illustrate the use of ‘super’ Keyword ?

Ans: ‘super’ keyword is used inside a sub-class method definition to call a method defined in
the super class. Private methods of the super-class cannot be called. Only public and protected
methods can be called by the super keyword.

 It is also used by class constructors to invoke constructors of its parent class.

Syntax:

super.<method-name>([zero or more arguments]);

OR

super ([zero or more arguments]);


Q6)Illustrate the use of final keyword ?

Ans: To disallow a method from being overridden, specify final as a modifier at the start of its
declaration. Methods declared as final cannot be overridden. The following fragment illustrates
final:
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a
compile-time error will result. However, since final methods cannot be overridden, a call to one
can be resolved at compile time. This is called early binding.
Sometimes we want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final,
too. It is illegal to declare a class as both abstract and final since an abstract class is incomplete
by itself and relies upon its subclasses to provide complete implementations. Here is an example
of a final class:

final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
It is illegal for B to inherit A since A is declared as final.

Q7)How is inheritance incorporated in java?

Ans: It is possible to acquire all the members of a class and use them in another class by relating
the objects of the two classes. This is possible by using inheritance concept. When a class is
written by a programmer and another programmer wants the same features (members) in his
class also, then the other programmer will go for inheritance. This is done by deriving the new
class from the existing class.
Inheritance is a concept where new classes can be produced from existing classes. The newly
created class acquires all the features of existing class from where it is derived.

Example:
Q8)What is dynamic method dispatch or Run time polymorphism?

Ans:The polymorphism exhibited at runtime called dynamic polymorphism. This means when
method is called, the method call is bound to the method body at the time of running the program
dynamically. In this case, Java compiler does not know which method is called at the time of
compilation. Only JVM knows at runtime which method is to be executed. Hence, this is also
called Rxun time polymorphism.

Example:
Q9)What is Abstract class?What is the use of Abstract class?

(BY H.S)

Ans: A class which contains the abstract keyword in its declaration is known as abstract class.

 Abstract classes may or may not contain abstract methods, i.e., methods without body (

public void get(); )

 But, if a class has at least one abstract method, then the class must be declared abstract.

 If a class is declared abstract, it cannot be instantiated.

 To use an abstract class, you have to inherit it from another class, provide

implementations to the abstract methods in it.

 If you inherit an abstract class, you have to provide implementations to all the abstract

methods in it.

Example:
abstract class Add
{
abstract int sum(int a,int b);
}
Q10) Define a) Single Level Inheritance b) Multi Level Inheritance c) Hierarchical
Inheritance?
Ans:There are various types of inheritance, based on paradigm and specific language.
a)Single Level Inheritance is where subclasses inherit the features of one superclass. A particular
class acquires the properties of another class.

Program:
class A
{void disp()
System.out.println(“Your name”);}
class B extends A
{void colg()
System.out.println(“Your College”);}
class C
{public static void main(String args[])
{B obj=new B();
obj.disp();
obj.colg();}
}
Output:
Your name
Your College

b)If class C inherits class B and class B inherits class A which means B is a parent class of C and
A is a parent class of B. So in this case class C is implicitly inheriting the properties and method
of class A along with B that's what is called multilevel inheritance.

Program:
class A
{void disp()
System.out.println("Your name");}
class B extends A
{void colg()
System.out.println("Your college");}
class C extends B
{void dept()
System.out.println("Your department");}

class X
{public static void main(String args[])
{C obj=new C();
obj.disp();
obj.dept();}
}
Output:
Your name
Your department

c) Hierarchical Inheritance is where one class serves as a superclass (base class) for more than
one sub class.

Program:
class A
{void disp()
System.out.println("Your name");}

class B extends A
{void colg()
System.out.println("Your college");}
class C extends A
{void dept()
System.out.println("Your department");}
class X
{public static void main(String args[])
{A obj=new A();
obj.disp();
obj.colg();
obj.dept();}
}

Output:
Your name
Your college
Your department

INTERVIEW QUESTIONS

Q1)What is inheritance?
Ans:Deriving new classes from existing classes such that the new classes acquire all the features
of existing classes is called inheritance.

Q2)Why super class members are available to sub class?


Ans:Because, the sub class object contains a copy of super class object.

Q3)What is the advantage of inheritance?From(N.RAO)


Ans:In inheritance, a programmer reuses the super class code without rewriting it, in creation of
sub classes. So, developing the classes becomes vel}' easy. Hence, the programmer's
protiuctivity is increased.

Q4) Why multiple inheritance is not available in java?

Ans:

It leads to confusion for a java program

 The programmer can archive multiple inheritance by using interfaces


 The programmer can archive multiple inheritance by repeatedly using single inheritance.

Q5)How Inheritance can be implemented in java?

Ans:Inheritance can be implemented in JAVA using below two keywords:

1.extends

2.implements

extends is used for developing inheritance between two classes and two interfaces.

implements keyword is used to developed inheritance between interface and class.

Q6)what is coercion ?

Ans:Type coercion is a means to convert one data type to another. For example, parsing the
Java String "42" to the Integer 42 would be coercion. Or more simply, converting a Long 42 to
a Double 42.0.

Q7)What is conversion?

Ans: When you assign value of one data type to another, the two types might not be compatible
with each other. If the data types are compatible, then Java will perform the conversion
automatically known as Automatic Type Conversion and if not then they need to be casted or
converted explicitly. For example, assigning an int value to a long variable.

Q8) What is method signature?

Ans: Method signature represents the method name along with method parameters.

Q9)What is method overloading?


Ans: In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case, the
methods are said to be overloaded, and the process is referred to as method overloading. Method
overloading is one of the ways that Java supports polymorphism. When an overloaded method is
invoked, Java uses the type and/or number of arguments as its guide to determine which version
of the overloaded method to actually call. Thus, overloaded methods must differ in the type
and/or number of their parameters. While overloaded methods may have different return types,
the return type alone is insufficient to distinguish two versions of a method. When Java
encounters a call to an overloaded method, it simply executes the version of the method whose
parameters match the arguments used in the call.

Q10)What is the difference between over loading and over riding ?

Ans:

1. Overloading happens at compile-time while Overriding happens at runtime: The binding of


overloaded method call to its definition has happens at compile-time however binding of
overridden method call to its definition happens at runtime.

2.Static methods can be overloaded which means a class can have more than one static method
of same name. Static methods cannot be overridden, even if you declare a same static method in
child class it has nothing to do with the same method of parent class.

3.The most basic difference is that overloading is being done in the same class while for
overriding base and child classes are required. Overriding is all about giving a specific
implementation to the inherited method of parent class.

4.Static binding is being used for overloaded methods and dynamic binding is being used for
overridden/overriding methods.

5.Performance: Overloading gives better performance compared to overriding. The reason is that
the binding of overridden methods is being done at runtime.

6.private and final methods can be overloaded but they cannot be overridden. It means a class
can have more than one private/final methods of same name but a child class cannot override the
private/final methods of their base class.

7.Return type of method does not matter in case of method overloading, it can be same or
different. However in case of method overriding the overriding method can have more specific
return type (refer this).

8.Argument list should be different while doing method overloading. Argument list should be
same in method Overriding.
Q12)Can you override private methods?

Ans:No. Private methods are not available in sub-classes so they cannot be overridden.
Q.13)Can you take private and final methods as same?

Ans: Yes. The java compiler assigns the value for the private methods at the time of compilation.
Also, private methods can’t be modified at run time. This is the same case with final methods
also. Neither the private methods nor the final methods can be over written so private methods
can be taken as final methods.

Q14) What is Abstract Method?


Ans: An abstract method is a method that is declared, but contains no implementation. Abstract
classes may not be instantiated, and require subclasses to provide implementations for
the abstract methods.
Q15) Can you take private and final methods as same?

Ans:Yes. The Java compiler assigns the value for the private methods at the time of compilation.
Also, private methods cannot be modified at run time. This is the same case with final methods
also. Neither the private methods nor the final methods can be overridden. So, private methods
can be taken as final methods.
INTERFACE

Multiple Choice Questions and Answers

i) Because finalize() beongs to the java.lang.Object class, it is present in all


a) Objects b) Classes c) Methods d)Variables
ii) Which are the keywords in java?
a) NULL b) Size of c) extends d)Friends
iii) The immediate super class of the applet class is
a) Panel b)Interface c)Object d)Window
iv) An interface can define only
a) Abstract class b) Final field c)Abstract method
d)Abstract method and final field
v) A constructor can be inherited using the keyword
a) Final b)Static c)Super d)none of these
vi) To inherit an interface from a class, we use the keyword
a) implements b)extends c)both a & b d)none of these
vii) How many default constructor can a class have when it has contructor?
a) 1 b)0 c)2 d)Any number
viii) String s = “WBUT”;
System.out.println(s.char At(2));
The output is
a) U b)Exception occurs c)2 d)B
ix) The error on executing the following code snippet will be :
abstract class xy
{
abstract sum (int x, int y){}
}

a) Class header is not defined properly b)No error


c)Method is not defined properly d)Constructor is not defined
x) Dynamic method dispatcher is used for
a) Resolving method overriding
b) Resolving multilevel inheritance
c) Resolving multiple inheritance anomaly
d) None of these
Question- Answer
Q1. Difference between Abstract class & interface?

Ans.

Sl Interface Abstract Class


No.
1. Multiple inheritance is possible, a class can inherit Multiple inheritance is not possible,
any number of interfaces. a class can inherit only one class.
2. implements keyword is used to inherit an Extends keyword is used to inherit
interface. a class.
3. By default, all methods in an interface are public Methods have to be tagged as
and abstract, no need to tag it as public and public or abstract or both, if
abstract. required.
4. All methods of an interface need to be overridden. Only abstract methods need to be
overridden.
5. All variables declared in an interface are by default Variables, if required have to be
public, static , and final. declared as public, static , or final.
6. Interfaces do not have any constructors. Abstract classes can have
constructors.
7. Methods in an interface cannot be static. Non abstract methods can be static.

Q2.What is interface?

Ans.An interface is a specification of method prototypes. All the methods of the interface are
public and abstract. An interface contains only abstract methods which are all incomplete
methods.

So, it is not possible to create an object of an interface. In this case, we can create separate
classes where we can implement all the methods of the interface .The classes are called
implementation classes.

Inheritance of interface is done using implements keyword.

Q3.Write a program to show that JAVA supports multiple inheritances by using interface.

Ans.

//Multiple inheritance using interfaces

interface Father
{
float HT=6.2f;
void height();
}
interface Mother
{
float HT= 5.8f;
void height();
}
class child implements Father,Mother
{
public void height()
{
floatht = (Father.HT+Mother.HT)/2;
System.out.println("Chlid's height="+ht);
}
}
class Multi
{
public static void main(String[] args) {
child ch = new child();
ch.height();
}
}

Q4.Explain how java get benifited by using interface with the help of an example ?

ANS. Classes in Java cannot have more than one super class. But, a large number of real-life
applications require the use of multiple inheritance whereby we inherit methods and properties
from several distinct classes. Java provides an alternate approach known as interface to support
the concept of multiple inheritance. Although a Java class cannot be a subclass of more than one
super class, it can implement more than one interface.

interface A

{
int x=20;
void method( );
}
interface B
{
int x=30;
void method ( );
}

There are several reasons, an application developer needs an interface ,one of them is java's
feature to provide multiple interface at interface level. It allows to write flexible code, which can
added to handle future requirements. Some of the reasons, why we need interface are:

1)if we implements methods in subclasses, the callers will not be able to call them via the
interface (not common point where they are defined).

2)java 8 will introduce default implementation of methods inside the interface,but that should be
used as exception rather than rule.even java desiner used in that way,it was introduce to maintain
backward compatiblity along with supporting lambda expression.All evolution of stream
APIwaspossuble due to this change.

3)interfaces are the way to declare a contract for implemanting classes to fulfill;it's the primary
toll to create abstraction and decoupled designs between consumer and producers.

EXAMPLE

interface Area
{
final static float pi=3.14f;
float compute(float x, float y);
}
Class Rectangle inplements Area
{
public void compute(float x,float y)
{
return (x*y);
}
}
class circle implements area
{
public float compute (float x,float y)
{
return (pi*x*x);
}
}
class interface test
}
public static void main (string args[ ])
{
Rectangle rect=new rectangle ( );
circle cir =new circle( );
AREA area;
area=rect;
system.out.println("Area of rectangle="+area.compute(10,20));
area=cir;
system.out.println("Area of circle="+area.compute(10,20));
}
}

Q5.Is it possible in JAVA to implement multiple inheritances ?If not then how it is possible
explain.

Ans. We now that in multiple inheritence ,sub classes are derived from multiple super classes.if
two super classes having same name 's for their members(varibles and methods)then which
ember is inherited into the sub classes is the main confusion in multiple inheritence.This is the
resion,Javadoes'nt support the concept of the multiple inheritence.This confusion is reduced by
using multiple interfaces too achives multiple inheritences.Let us takes that two interfaces as:

interface A
{
int x=20;
void method( );
}
interface B
{
int x=30;
void method ( );
}

And there is an implementation class myclass as:

Class my class implements a,b

Now, there is no confussion to reffer to any of the members of the interfaces from myclass. For
example,toreffer to interface A'sX, we can write:

A.X

And to reffer to interface B'sX, we can write:

B.X

Similarly there will not confussion regarding which method is avilable to the implementation
class, since both the methods in the interfaces do not have body,and the body is provided in the
implemention class ,i.e., my class

There way to achieve multiple inheritence by using interfaces is shown in Program 3.in this
program interface father has a constant HT which represents the height of father and interface
mother has another cont HT which represents height of the mother.Both the interfaces have an
abstruct method height ().If child is the implemention class of these of these interface,we can
write:

Class child implements father ,mother

Now in child class, we can use members of father and mother interfaces without any confussion
the height () method can be implemented in chlid class to calculate child's height which we
assuming being the average height of both the parents.

that two interfaces as:

interface A
{
int x=20;
void method( );
}
interface B
{
int x=30;
void method ( );
}

Interview Questions

Q1. Can you implement one interface from another?

Ans: No, we can’t. Implementing an interface means writing body for the methods. Since none
of the methods of the interface can have body.

Q2. Why the methods of interface are public and abstract are by default?

Ans: Interface methods are public since they should be

Das könnte Ihnen auch gefallen