Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
77 views

Java Questions

Java features include: 1. It is simple with C++-like syntax and automatic garbage collection. 2. It is object-oriented with basic concepts like classes, inheritance, polymorphism and abstraction. 3. It is platform independent as bytecode can run on any system with a Java virtual machine.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Java Questions

Java features include: 1. It is simple with C++-like syntax and automatic garbage collection. 2. It is object-oriented with basic concepts like classes, inheritance, polymorphism and abstraction. 3. It is platform independent as bytecode can run on any system with a Java virtual machine.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Q1) Explain features of java?

Simple

According to Sun, Java language is simple because:

syntax is based on C++ (so easier for programmers to learn it after C++).

removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.

No need to remove unreferenced objects because there is Automatic Garbage


Collection in java.

Object-oriented

Object-oriented means we organize our software as a combination of different types of


objects that incorporates both data and behaviour.

Object-oriented programming(OOPs) is a methodology that simplify software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class

3. Inheritance

4. Polymorphism

5. Abstraction

6. Encapsulation

Platform Independent

A platform is the hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides
software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:
1. Runtime Environment

2. API(Application Programming Interface)

Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is
a platform-independent code because it can be run on multiple platforms i.e. Write Once
and Run Anywhere(WORA).

Secured

Java is secured because:

o No explicit pointer
o Java Programs run inside virtual machine sandbox

o Classloader: adds security by separating the package for the classes of the local
file system from those that are imported from network sources.
o Bytecode Verifier: checks the code fragments for illegal code that can violate
access right to objects.
o Security Manager: determines what resources a class can access such as
reading and writing to the local disk.

These security are provided by java language. Some security can also be provided by
application developer through SSL, JAAS, Cryptography etc.

Robust
Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points
makes java robust.

Architecture-neutral

There is no implementation dependent features e.g. size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for
both 32 and 64 bit architectures.

Portable

We may carry the java bytecode to any platform.

High-performance

Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)

Distributed

We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any machine
on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications etc.
Q2)Write a short note on jvm?

A Java virtual machine (JVM), an implementation of the Java Virtual


Machine Specification, interprets compiled Java binary code (called bytecode)
for a computer's processor (or "hardware platform") so that it can perform a
Java program's instructions. Java was designed to allow application programs
to be built that could be run on any platform without having to be rewritten or
recompiled by the programmer for each separate platform. A Java virtual
machine makes this possible because it is aware of the specific instruction
lengths and other particularities of the platform.

The Java Virtual Machine Specification defines an abstract -- rather than a


real -- machine or processor. The Specification specifies an instruction set,
a set of registers, a stack, a "garbage heap," and a method area. Once a Java
virtual machine has been implemented for a given platform, any Java
program (which, after compilation, is called bytecode) can run on that
platform. A Java virtual machine can either interpret the bytecode one
instruction at a time (mapping it to a real processor instruction) or the
bytecode can be compiled further for the real processor using what is
called a just-in-time compiler.

Q3) Explain java leterals ?

ava Literals are syntactic representations of boolean, character, numeric, or string data. Literals
provide a means of expressing specific values in your program. For example, in the following
statement, an integer variable named count is declared and assigned an integer value. The
literal 0 represents, naturally enough, the value zero.
Code section 3.61: Numeric literal.

1 int count = 0;

The code section 3.62 contains two number literals followed by two boolean literals at line 1, one
string literal followed by one number literal at line 2, and one string literal followed by one real
number literal at line 3:

Code section 3.62: Literals.

1 (2 > 3) ? true : false;


2 "text".substring(2);
3 System.out.println("Display a hard coded float: " + 37.19f);
Boolean Literals[edit]

There are two boolean literals

 true represents a true boolean value


 false represents a false boolean value

There are no other boolean literals, because there are no other boolean values!

Numeric Literals[edit]

There are three types of numeric literals in Java.

Integer Literals[edit]

In Java, you may enter integer numbers in several formats:

1. As decimal numbers such as 1995, 51966. Negative decimal numbers such as -42 are
actually expressions consisting of the integer literal with the unary negation operation -.
2. As octal numbers, using a leading 0 (zero) digit and one or more additional octal digits (digits
between 0 and 7), such as 077. Octal numbers may evaluate to negative numbers; for
example 037777777770 is actually the decimal value -8.
3. As hexadecimal numbers, using the form 0x (or 0X) followed by one or more hexadecimal
digits (digits from 0 to 9, a to f or A to F). For example, 0xCAFEBABEL is the long integer
3405691582. Like octal numbers, hexadecimal literals may represent negative numbers.
4. Starting in J2SE 7.0, as binary numbers, using the form 0b (or 0B) followed by one or more
binary digits (0 or 1). For example, 0b101010 is the integer 42. Like octal and hex numbers,
binary literals may represent negative numbers.

By default, the integer literal primitive type is int. If you want a long, add a letter el suffix
(either the character l or the character L) to the integer literal. This suffix denotes a long
integer rather than a standard integer. For example, 3405691582L is a long integer literal.
Long integers are 8 bytes in length as opposed to the standard 4 bytes for int. It is best
practice to use the suffix L instead of l to avoid confusion with the digit 1 (one) which looks
like l in many fonts: 200l ≠ 2001. If you want a short integer literal, you have to cast it.

Starting in J2SE 7.0, you may insert underscores between digits in a numeric literal. They are
ignored but may help readability by allowing the programmer to group digits.

Floating Point Literals[edit]

Floating point numbers are expressed as decimal fractions or as exponential notation:

Code section 3.63: Floating point literals.


1 double decimalNumber = 5.0;
2 decimalNumber = 5d;
3 decimalNumber = 0.5;
4 decimalNumber = 10f;
5 decimalNumber = 3.14159e0;
6 decimalNumber = 2.718281828459045D;
7 decimalNumber = 1.0e-6D;

Floating point numbers consist of:

1. an optional leading + or - sign, indicating a positive or negative value; if omitted, the value is
positive,
2. one of the following number formats
o integer digits (must be followed by either an exponent or a suffix or both, to
distinguish it from an integer literal)
o integer digits .
o integer digits . integer digits
o . integer digits
3. an optional exponent of the form
o the exponent indicator e or E
o an optional exponent sign + or - (the default being a positive exponent)
o integer digits representing the integer exponent value
4. an optional floating point suffix:
o either f or F indicating a single precision (4 bytes) floating point number, or
o d or D indicating the number is a double precision floating point number (by default,
thus the double precision (8 bytes) is default).

Here, integer digits represents one or more of the digits 0 through 9.

Starting in J2SE 7.0, you may insert underscores between digits in a numeric literal. They are
ignored but may help readability by allowing the programmer to group digits.

Character Literals[edit]

Character literals are constant valued character expressions embedded in a Java program.
Java characters are sixteen bit Unicode characters, ranging from 0 to 65535. Character literals
are expressed in Java as a single quote, the character, and a closing single quote ('a', '7',
'$', 'π'). Character literals have the type char, an unsigned integer primitive type.
Character literals may be safely promoted to larger integer types such as int and long.
Character literals used where a short or byte is called for must be cast to short or byte
since truncation may occur.

String Literals[edit]

String literals consist of the double quote character (") (ASCII 34, hex 0x22), zero or more
characters (including Unicode characters), followed by a terminating double quote character
("), such as: "Ceci est une string."

So a string literal follows the following grammar:

<STRING :
"\""
( (~["\"","\\","\n","\r"])
|("\\"
( ["n","t","b","r","f","\\","'","\""]
|["0"-"7"](["0"-"7"])?
|["0"-"3"]["0"-"7"]["0"-"7"]
)
)
)*
"\"">

Within string and character literals, the backslash character can be used to escape special
characters, such as unicode escape sequences, or the following special characters:

Name Character ASCII hex


Backspace \b 8 0x08
TAB \t 9 0x09
NUL character \0 0 0x00
newline \n 10 0x0a
carriage control \r 13 0xd
double quote \" 34 0x22
single quote \' 39 0x27
backslash \\ 92 0x5c

String literals may not contain unescaped newline or linefeed characters. However, the Java
compiler will evaluate compile time expressions, so the following String expression results in
a string with three lines of text:

Code section 3.64: Multi-line string.


1 String text = "This is a String literal\n"
2 + "which spans not one and not two\n"
3 + "but three lines of text.\n";

null[edit]

null is a special Java literal which represents a null value: a value which does not refer to
any object. It is an error to attempt to dereference the null value — Java will throw a
NullPointerException. null is often used to represent uninitialized state.

Q4)differentiate between call by value and call by reference in java?

CALL BY VALUE:

Look at first example:

class Hello
{
void disp(int i,int j)
{
i*=2;
j/=2;
}
}

class T7
{
public static void main(String as[])
{
int a=99;
int b=77;

System.out.println("before call");
System.out.println("a="+a);
System.out.println("b="+b);

Hello h=new Hello();


h.disp(a,b);
System.out.println("AFTER call");
System.out.println("a="+a);
System.out.println("b="+b);

}
}

OUTPUT:

before call
a=99
b=77
AFTER call
a=99
b=77

When you pass a simple type to a method, it is passed by value. Thus what occurs to the
parameter that receives the argument has no effect outside the method. Here the
operation occur inside disp() have no effect on the values of a and b used in the call.
Their values didn't change to 198 and 38.
CALL BY REFERENCE:

class Hello
{
int a,b;
Hello(int i,int j)
{
a=i;
b=j;
}
void disp(Hello o) //pass an object
{
o.a*=2;
o.b/=2;
}
}

class T6
{
public static void main(String as[])
{
Hello h=new Hello(15,20);
System.out.println("before call");
System.out.println("a="+h.a);
System.out.println("b="+h.b);
h.disp(h);
System.out.println("AFTER call");
System.out.println("a="+h.a);
System.out.println("b="+h.b);

}
}

OUTPUT:
before call
a=15
b=20
AFTER call
a=30
b=10

When you pass an object to a method the situation change dramatically. Because objects
are passed by Reference. When you creating a variable of a class type , you are only
creating a reference to an object. change to the object inside the method do effect the
object used as an argument. When object reference is passed to a method, the reference
itself is passed by use of call-by-value.

Q5)Explain static keyword along with its example?

The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.

The static can be:

1. variable (also known as class variable)

2. method (also known as class method)

3. block

4. nested class

1) Java static variable


If you declare any variable as static, it is known static variable.

o The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees,college name of
students etc.

o The static variable gets memory only once in class area at the time of class
loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created.All student have its unique rollno and name so
instance data member is good.Here, college refers to the common property of all
objects.If we make it static,this field will get memory only once.
Java static property is shared to all objects.

Example of static variable


1. //Program of static variable
2.
3. class Student8{
4. int rollno;
5. String name;
6. static String college ="ITS";
7.
8. Student8(int r,String n){
9. rollno = r;
10. name = n;
11. }
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13.
14. public static void main(String args[]){
15. Student8 s1 = new Student8(111,"Karan");
16. Student8 s2 = new Student8(222,"Aryan");
17.
18. s1.display();
19. s2.display();
20. }
21. }
Test it Now

Output:111 Karan ITS

222 Aryan ITS

2) Java static method


If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than object of a class.

o A static method can be invoked without the need for creating an instance of a
class.

o static method can access static data member and can change the value of it.
o //Program to get cube of a given number by static method
o
o class Calculate{
o static int cube(int x){
o return x*x*x;
o }
o
o public static void main(String args[]){
o int result=Calculate.cube(5);
o System.out.println(result);
o }
o }

Output:125

Restrictions for static method

There are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method directly.

2. this and super cannot be used in static context.

why java main method is static?

Ans) because object is not required to call static method if it were non-static method,
jvm create object first then call main() method that will lead the problem of extra
memory allocation.

3) Java static block


o Is used to initialize the static data member.

o It is executed before main method at the time of classloading.

Example of static block


1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Test it Now

Output:static block is invoked

Hello main

Q) Can we execute a program without main() method?

Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Test it Now

Output:static block is invoked (if not JDK7)

In JDK7 and above, output will be:

Output:Error: Main method not found in class A3, please define the main method as:

public static void main(String[] args)

Q6)Write a short note on GC?

Java Garbage Collection


In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically.


In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java
it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes the


unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
How can an object be unreferenced?
There are many ways:

o By nulling the reference

o By assigning a reference to another

o By annonymous object etc.

1) By nulling a reference:

1. Employee e=new Employee();


2. e=null;

2) By assigning a reference to another:

1. Employee e1=new Employee();


2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:

1. new Employee();

finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class as:

1. protected void finalize(){}

Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
1. public static void gc(){}

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC).


This thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java


1. public class TestGarbage1{
2. public void finalize(){System.out.println("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. System.gc();
9. }
10. }
Test it Now

object is garbage collected

object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

Q7)Differntiate between overloading and overriding in java?

There are many differences between method overloading and method overriding in java.
A list of differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the readability of the Method overriding is u


program. specific implementation
already provided by its s

2) Method overloading is performed within class. Method overriding occur


have IS-A (inheritance) r

3) In case of method overloading, parameter must be different. In case of method overr


be same.
4) Method overloading is the example of compile time polymorphism. Method overriding is the
polymorphism.

5) In java, method overloading can't be performed by changing return Return type must be s
type of the method only. Return type can be same or different in method overriding.
method overloading. But you must have to change the parameter.

Java Method Overloading example


1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }

Java Method Overriding example


1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }

Q8)What is inner class and nested class along with example?

A class declared inside a class is known as nested class. We use nested classes to logically
group classes in one place so that it can be more readable and maintainable code.
Moreover, it can access all the members of outer class including private members.

Syntax of Nested class

class OuterClass {

...

class NestedClass {

...

}
difference between nested class and inner class?
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static
are simply called static nested classes. Non-static nested classes are called inner classes. Inner class is a
part of nested class. Non-static nested classes are known as inner classes.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to
other members of the enclosing class, even if they are declared private. Static nested classes do not have
access to other members of the enclosing class. As a member of the OuterClass, a nested class can be
declared private, public, protected, or package private. (Recall that outer classes can only be declared
public or package private.)

Why Use Nested Classes?


There are several compelling reasons for using nested classes, among them:

1. It is a way of logically grouping classes that are only used in one place.
2. It increases encapsulation.
3. Nested classes can lead to more readable and maintainable code.
 Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed
it in that class and keep the two together. Nesting such “helper classes” makes their package more
streamlined.
 Increased encapsulation—Consider two top-level classes, A and B, where B needs access to
members of A that would otherwise be declared private. By hiding class B within class A, A’s
members can be declared private and B can access them. In addition, B itself can be hidden from the
outside world.
 More readable, maintainable code—Nesting small classes within top-level classes places the code
closer to where it is used.
Types of Nested class:
There are two types of nested classes non-static and static nested classes.The non-static nested classes are
also known as inner classes.
1. non-static nested class(inner class)
 a)Member inner class
 b)Annomynous inner class
 c)Local inner class
2. static nested class
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static
class methods, a static nested class cannot refer directly to instance variables or methods defined in its
enclosing class — it can use them only through an object reference.

Note: A static nested class interacts with the instance members of its outer class (and other classes) just
like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been
nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject =

new OuterClass.StaticNestedClass();

Inner Classes
As with instance methods and variables, an inner class is associated with an instance of its enclosing class
and has direct access to that object’s methods and fields. Also, because an inner class is associated with an
instance, it cannot define any static members itself.
Objects that are instances of an inner class exist within an instance of the outer class. Consider the
following classes:

class OuterClass {

...

class InnerClass {

...

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the
methods and fields of its enclosing instance. The next figure illustrates this idea.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within
the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Additionally, there are two special kinds of inner classes: local classes and anonymous classes.

Q9)Define?

1) Byte code?
Java bytecode is the result of the compilation of a Java program, an
intermediate representation of that program which is machine independent.

The Java bytecode gets processed by the Java virtual machine (JVM) instead
of the processor. It is the job of the JVM to make the necessary resource calls
to the processor in order to run the bytecode.
Java bytecode is the result of the compilation of a Java program, an
intermediate representation of that program which is machine independent.
The Java bytecode gets processed by the Java virtual machine (JVM) instead
of the processor. It is the job of the JVM to make the necessary resource calls
to the processor in order to run the bytecode.
2) class?

A class is a group of objects which have common properties. It is a template or blueprint


from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o fields
o methods
o constructors
o blocks
o nested class and interface

Syntax to declare a class:

1. class <class_name>{
2. field;
3. method;
4. }
3) Object?

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tangible and intangible). The example of
intangible object is banking system.

An object has three characteristics:

o state: represents data (value) of an object.


o behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
o identity: Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. But, it is used internally by the JVM to
identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects


are created. So object is the instance(result) of a class.

Object Definitions:

o Object is a real world entity.


o Object is a run time entity.
o Object is an entity which has state and behavior.
o Object is an instance of a class.

4) Constructor?

In Java, constructor is a block of codes similar to method. It is called when an instance


of object is created and memory is allocated for the object.

It is a special type of method which is used to initialize the object.

Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name

2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors in java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Q10) Explain inheritance and its types along with example?

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called parent or super class and
the new class is called child or subclass.

Java Inheritance Example


As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A Employee.It means
that Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now

Programmer salary is:40000.0

Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface


only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:
Single Inheritance Example
File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...

eating...

Multilevel Inheritance Example


File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...

barking...

eating...

Hierarchical Inheritance Example


File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:

meowing...

eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object,
there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error now.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now

Compile Time Error

You might also like