Java1 New
Java1 New
Java1 New
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.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.
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:
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.
Output:
}
}
Output:
}
}
Output:
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:
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.
Q7. Which of these keyword can be used in subclass to call the constructor of superclass?
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
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
INHERITANCE:-
Deriving new classes from existing classes such that the new classes acquire all the features of
existing classes is called 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
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.
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.
Syntax:
OR
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.
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 (
But, if a class has at least one abstract method, then the class must be declared abstract.
To use an abstract class, you have to inherit it from another class, provide
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.
Ans:
1.extends
2.implements
extends is used for developing inheritance between two classes and two interfaces.
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.
Ans: Method signature represents the method name along with method parameters.
Ans:
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.
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
Ans.
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.
Q3.Write a program to show that JAVA supports multiple inheritances by using interface.
Ans.
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 ( );
}
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
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:
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.
interface A
{
int x=20;
void method( );
}
interface B
{
int x=30;
void method ( );
}
Interview Questions
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?
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: