• ▼Java Exercises
  • Basic Part-I
  • Basic Part-II
  • Conditional Statement
  • Recursive Methods
  • Java Enum Types
  • Exception Handling
  • Java Inheritance
  • Java Abstract Classes
  • Java Thread
  • Java Multithreading
  • Java Lambda expression
  • Java Generic Method
  • Object-Oriented Programming
  • Java Interface
  • Java Encapsulation
  • Java Polymorphism
  • File Input-Output
  • Regular Expression
  • ▼JavaFx Exercises
  • JavaFx Exercises Home
  • ..More to come..

Java Inheritance: Exercises, Practice, Solution

Java inheritance exercises [10 exercises with solution].

From Oracle -

Java Inheritance: In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.

Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.

[ An editor is available at the bottom of the page to write and execute the scripts.   Go to the editor ]

Click me to see the solution

Java Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Java Inheritance Quiz Practice Coding Questions

pramodbablad

  • October 25, 2015
  • Java Practice Coding Questions

88 Comments

In this post, there are some 40 Java inheritance quiz type questions and answers which will help you to understand Java inheritance concept better.

Java Inheritance Quiz Practice Coding Questions :

1) Tinku has written the code like below. But, it is showing compile time error. Can you identify what mistake he has done?

2) What will be the output of this program?

Java inheritance quiz

3) What will be the output of the below program?

4) Can a class extend itself?

5) What will be the output of the following program?

6) What will be the output of this program?

7) What will be the output of the below program?

8) Private members of a class are inherited to sub class. True or false?

9) What will be the output of the following program?

10) Below code is showing compile time error. Can you suggest the corrections?

11) What is wrong with the below code? Why it is showing compile time error?

12) You know that compiler will keep super() calling statement implicitly as a first statement in every constructor. What happens if we write this() as a first statement in our constructor?

13) Can you find out the error in the below code?

14) Which class is a default super class for every class in java?

15) Can you find out the error in the below code?

16) What will be the output of this program?

17) What will be the output of the below program?

18) What will be the output of the following program?

19) Why Line 10 in the below code is showing compilation error?

20) What will be the output of the below program?

21) What will be the output of this program?

22) What will be the output of the following program?

23) What happens if both super class and sub class have a field with same name?

24) Does the below program execute successfully? If yes, what will be the output?

25) How do you prevent a field or a method of any class from inheriting to sub classes?

26) What will be the output of the below program?

27) Does java support multiple inheritance?

28) What will be the output of this program?

29) Does the fields with default visibility inherited to sub classes outside the package?

30) Constructors are also inherited to sub classes. True or false?

31) What will be the output of the below program?

32) What happens if both super class and sub class have a field with same name?

33) What will be the output of the below program?

34) What will be the outcome of the following program?

35) Can a class be extended by more than one classes?

36) Does the below program written correctly? If yes, what will be the output?

37) Does the below code prints “Hi….” on the console? If yes, how many times?

38) What value the fields ‘i’ and ‘j’ will hold when you instantiate ‘ClassTwo’ in the below code?

39) When you instantiate a sub class, super class constructor will be also executed. True or False?

40) Does the below code written correctly? If yes, what will be the output?

Also Read :

  • Classes & Objects Quiz
  • Polymorphism Quiz
  • Abstract Classes Quiz
  • Java Interfaces Quiz
  • Java Modifiers Quiz
  • Nested Classes Quiz
  • Java Enums Quiz
  • i++, i– & ++i, –i Quiz
  • Java Arrays Quiz
  • Java Strings Quiz
  • Java Inheritance Oracle Docs
  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Telegram (Opens in new window)

Related Posts

Java exception handling quiz.

  • December 13, 2022

Java Threads Quiz

  • November 26, 2022

60+ Java Strings Quiz Questions

  • October 20, 2021

Q 38 ) pls cross-verify the o/p of Q38. class ClassOne { static int i = 111;

int j = 222;

{ i = i++ – ++j; System.out.println(i); }

class ClassTwo extends ClassOne {

{ j = i– + –j; System.out.println(j); } }

public class MainClass { public static void main(String[] args) { ClassTwo two = new ClassTwo();

o/p- -112 110

Yes, I am also getting the same out put -112 110

in question 38, line number 15; that is j = i– + –j;

value of “i” will get decremented from -112 to -113 so the final value of i is -113

in question 38, line number 15; that is j = i– + –j;

value of “i” will get same value 111(i-) + (-j) j value will get decremented 221 so the final value is 332

class ClassOne { static int i = 111; int j = 222; { i = i++ – ++j; // i = 111(increment after instruction execution) – 223(increment before execution) => i = -112 , j =223 } } class ClassTwo extends ClassOne { { j = i– + –j; => j = -112(decrement after execution) + 222(decrement before execution) => j = 110 && i gets decremented after execution => i = -112-1 = -113 } } Hence i = -113, j=110 at the end

its giving error: non-static variable j cannot be referenced from a static context System.out.println(“i: ” + i +”\n” + “j: ” + j);

my code : class ClassOne { static int i = 111;

{ i = i++ – ++j; } }

public class ClassTwo extends ClassOne { public static void main(String [] args) { System.out.println(“i: ” + i +”\n” + “j: ” + j); }

{ j = i– + –j; }

i also gt sm otpt

variable j must be static static int j=222; then error will be removed but output same as given value output:111 222 becoz your all of instance block is not exicuted. it will be exicute during the class object creation. if you write this statenment in main method so all of instance block will exicute. ClassTwo obj1=new ClassTwo();

print the value of i and j in main class then the output will be -113 110

yes the output is wrong in the answer.

yes,output is wrong. correct output is -112 for i 110 for j

For Q.38), output is right. Try it on any software like netbeans, or can use online compiler.

I am Confused, please correct me.

I believe, Question number 2 is wrong. Because A a = new B() and a.i should be = 20.

Hi pri, It points to the type of the reference it is referred to, not the type of the reference it is assigned.

In case of overriding of method, it is reverse and it is so called Runtime Method Dispatch

hello divya can you please elaborate?

for eg. what would be the output in the following?

lass Animal{

public void move(){ System.out.println(“Animals can move”); } }

class Dog extends Animal{

public void move(){ System.out.println(“Dogs can walk and run”); } }

public class TestDog{

public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class

For me, both seems the same. Please enlighten me on this !!!

Hello Ash, the example u gave was of Run-time polymorphism, when u give reference of subclass to parent class variable and are calling the subclass method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime.

and in question no. 2 he is trying to do the same but Method is overridden not the datamembers, so runtime polymorphism can’t be achieved by data members. Since you are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

animals can move dogs can walk and run

Hi pri This is variable not method variable not comes under overriding so its work as a overloading

I got the same view on it

i also think so.

the answer is true b/c it is a rule in java when is being created then control goes through parent class if it exist

Variables cannot be overloaded bro…

in 28 question i value not declared but it becomes 1 how is it

i is initialized to 0 in Parent Class and Child Class can access it has default access specifier. Execution Flow: All static blocks are executed, since there are no constructor’s initializer blocks are not executed.

please explain the line number 6 of question 20 m = m++;

There is a solution my friend

M=1111 is initialized .

When compiler goes to the statement

M=m++; then the processing of code is Firstly m++ is a post increament value so it follows first use then change so without changing to1112 it assigns 1111 to M.

Thats y we r getting output 1111.

if you compile only m++ and not assigning this m++ to M then definitely u will get 1112.

hope it helps you.

Q 26) Can enay explain below b.a.i = 2121;

System.out.println(“——–“);

System.out.println(a.i);

System.out.println(b.i);

Output: ———- ——– 2121 1212

Yes, b’s reference to (A a) actually points to the ‘a’ that was instantiated with this statement A a = new A();. This statement B b = new B(a); Notice the ‘a’ as an argument to the constructor. b’s b.a actually points to ‘a’. So b.a.i changes a’s int i.

can u explain question no 5

can u plzz explain 20 question

are u say Q20# or total 1-20 questions?

class A { int i = 10; }

class B extends A { int i = 20; }

public class MainClass { public static void main(String[] args) { A a = new B();

System.out.println(a.i); } }

This calls the parent class variable. But

class A { int i = 10;

public void print() { System.out.println(“class A”); } }

class B extends A { int i = 20;

public void print() { System.out.println(“class B”); } }

public class MainClass { public static void main(String[] args) { A a = new B(); a.print();

It calls the child method. Its like same inheritance. Can anybody tell me how is this?

public void print() { System.out.println(“class A”); } }

public void print() { System.out.println(“class B”); } }

In this case method call is based on actual reference type.And here in this case you are passing the reference of parent class.Where as in another question your are orerriding the print method in its sub-class in that case method cal l is based on actual object passed to it.

why output is 10 instead of 20? class A { int i = 10; }

Its because when you override a variable it creates separate copy of the variable, one corresponds to superclass , the other one for subclass. So here, a is a superclass reference of the object of type B. So it’s referring to the A portion of the variable.

here the output is 10 instead of 20 because during time of overriding non static data member create their own distinct copy,

class A { String s = “Class A”; }

class B extends A { String s = “Class B”;

{ System.out.println(super.s); } }

class C extends B { String s = “Class C”;

public class MainClass { public static void main(String[] args) { C c = new C();

System.out.println(c.s); } } View Answer Answer : Class A Class B Class C according to me output is class C class b class a please explain why it’s reverse.

First of all, initialization block is been put inside constructor by compiler. Here default constructor is used by compiler. C c = new C(); –> here C() constructor is called & by default , compiler will call super constructor which is B(), but there is no constructor mentioned, it will call again default constructor for B class & as I said it will put initialization block inside constructor. So System.out.println(super.s); of class B will be executed first, (super.s) is “Class A”. After this System.out.println(super.s); of class C will be executed so “Class B” will be print Then System.out.println(c.s);–> “Class C”

class X { int m = 1111;

System.out.println(m); } }

class Y extends X { { System.out.println(methodOfY()); }

int methodOfY() { return m– + –m; } }

public class MainClass { public static void main(String[] args) { Y y = new Y(); } }

30) Constructors are also inherited to sub classes. True or false? Answer : false. Constructors, SIB and IIB are not inherited to sub classes. But, they are executed while instantiating a subclass.

but on question 28) the code is executing without instantiating the class, means SIB is executing and giving output. anyone plz explain me more on this.

SIBs are executed during class loading i.e., when a .class file is loaded but before even a class is instantiated(or not instantiated) during execution time. So in any program all the static blocks will be executed even if an instance is created or not.

Excellent stuff good for java people.

Question 10)

I thought super class constructor will be call automatically. why it is added super(10).

Can a class be extended by more than one classes? ans is NO question no 35 is wrong answer because multiple inheritance not support in java

class A { …… } class B extends A{ …….. } class C extends A{ …………. } The above code is what the question interprets, that means A can be a parent class for any number of classes. This is example for hierarchical Inheritance.

On the other hand multiple inheritance means a class extending more than one class at the same time i.e., For example: class A extends B,C which creates ambiguity.

class A{   void msg(){System.out.println(“Hello”);}   }   class B{   void msg(){System.out.println(“Welcome”);}   }   class C extends A,B{//suppose if it were        Public Static void main(String args[]){      C obj=new C();      obj.msg();//Now which msg() method would be invoked?   }   }  

O/p: Compile time error

The object is created for class C but msg() is not overridden. so compiler throws an error.

no , i think you misunderstand the question,question is “can we use base /parent/super class in more than one class its a hierarical inheritance |—-c2 |—-c3 c1—-> |—-c4 |—-c5

Can anybody explain me the qstn number 16….as well as qstn 20 output is why 2220 why not 2221……

class M { static { System.out.println(‘A’); }

{ System.out.println(‘B’); }

public M() { System.out.println(‘C’); } }

class N extends M { static { System.out.println(‘D’); }

{ System.out.println(‘E’); }

public N() { System.out.println(‘F’); } }

public class MainClass { public static void main(String[] args) { N n = new N(); } }

can anyone explain question no. 16?

Please Explain Q 18 ?

public N(int j)     {         super(j);           System.out.println(i);           this.i = j * 20;

When the above code starts executing as a per the Statement; N n = new N(26); At this point of time, super(j); will point the execution to

public M(int j)     {         System.out.println(i);           this.i = j * 10; }

And ‘i’ will be printed which is 51 at that time, then the instance variable ‘i’ will change since its value as per this.i = j * 10; where j is 26, which makes the value of i as 260.

So the o/p so far is 51

Now the execution is handed back to the constructor in the child class N constructor as shown below: public N(int j)     {         super(j);         System.out.println(i);         this.i = j * 20;} Now value of i at this instance(i.e., 260) is printed.

Next this.i = j * 20; is executed and the value of i now is 520.

which is printed when the print statement in the main() method is executed.

in a file the classes like class A and class B are inherited and they are public. And even the main Class also public, then in what name the file should be saved. import java.io.*; public class A { int i = 10; }

public class B extends A { int i = 20; }

Question 17 has compile time error because super class don’t have default constructor.

Can anyone explain the reason of question no-2

The object a is declared as type A but it will not be aware of the variable i in class B. if you try to change the declaration as B a = new B(); Then you will get 20.

Can anyone explain the following code in Q.No-26 System.out.println(b.a.i);

b.a.i = 2121;

Yes, b’s reference to (A a) actually points to the ‘a’ that was instantiated with this statement A a = new A();. This statement B b = new B(a); Notice the ‘a’ as an argument to the constructor. b’s b.a actually points to ‘a’. So b.a.i changes a’s int i.

is call by value, call by reference applicable here, or is it part of c++ only?

Hi Rahul, A a = new B(); this is called casting. This statement tells Child class (B) referencing to parent class (A), so parent class instance varible will be printed. If this code is replaced with B b = new B(); System.out.println(b.i); // you can see “20” output. here child class instance is referncing to child class variable.

To admin Answer of Q#2 is wrong .You should correct it. Its correct answer is 20

Answer 10 is correct, overriden is applied only method not on instance variable.

I also thinks it should be 20.

can anyone explain ques 26

Q10) can you please explain the flow of execution

please help explaining 20 detail

please explain q32

please modify the code for Question 1 to make it runnable

I have a query regarding question number 12. As you said “Compiler will not keep super() if you are writing this() as a first statement in your constructor.” Please refer blow code and output public class Test {

public static void main(String[] args) { Y y = new Y(10); } }

class X { X(){ System.out.println(“X class”); } }

class Y extends X { Y(){ System.out.println(“Y class”); }

Y(int i){ this(); System.out.println(“Y class : “+ i); } }

Actual Output : X class Y class Y class : 10

Expected output : Y class Y class : 10

So conclusion is “Compiler will always keep super() whether we are writing this() or not as a first statement in your constructor.” Please correct me if I did anything wrong.

Anyone explain question 28. How the value of i will become 1.

Thanks, brother. Nice Article, Great work…!?

class A { public A(){ System.out.println(” A”); } static { System.out.println(“THIRD”); } }

class B extends A {

public B(){ System.out.println(“B”); } static { System.out.println(“SECOND”); } }

class C extends B { static { System.out.println(“FIRST”); }

public C(){ System.out.println(“C”); } }

public class MainClass { public static void main(String[] args) { A c = new C(); } }

Q no 9: Why output is Class Y and why not it is : Class X Class Y

Please explain Q20.

Q 21 class A { static String s = “AAA”;

static { s = s + “BBB”; }

{ s = “AAABBB”; } }

class B extends A { static { s = s + “BBBAAA”; }

{ System.out.println(s); } }

public class MainClass { public static void main(String[] args) { B b = new B(); }

how is answer AAABBB . shouldn’t be AAABBBBBBAAA .

When the Object is created B b = new B() ; it calls the default constructor in B which in turns calls the default constructor of A .. where s = AAA , static function of A is executed which makes s as AAABBB then IIB is executed which makes s = AAABBB, then control goes back to Class B where SIB is executed where s = s + “BBBAAA” which makes s as AAABBBBBBAAA and then IIB is executed which prints AAABBBBBBAAA ? Isn’t it correct . Please explain .

Q 21 ) first static methods are executed then non-static so s will get “AAABBBBBBAAA” and then s = “AAABBB” will and then print statement.

for Q20 output is as follows: 1112 2222

you are not taking into consideration the decrement and assignment rules for “–“:

i = m–; // the value of m is decreased after m is assigned to i, so “i” doesn’t change: i = 1111 and m=1110 j= –m; // the value of m is decreased before m is assigned to j, so m = 1110 – 1 = 1109 and then the result will be assigned to j, j = 1109 z = i + j; // thus z = 1111 + 1109 = 2220

Could anyone please explain the execution flow of the program given in Q16?

it’s a nice code

plz explain Question 26 I don’t understand what is b.a.i

Answer of Q31 is 0

Please explain question. 16 I didn’t understand the order of execution.

public class MainClass { public static void main(String[] args) { N n = new N(); } } //output : A D B C E F

==> We know that static block will be execute before the main ( So A & D will be printed at the top ) ==> Now the child class created an object for its own class and its constructor get invoked A child class constructor has super class as default so parent class constructor invoked and prints B & C, later child class constructors get printed E & F

Hi Can i have an explanation for number 5 , my answer was Class A only and yet also B and C are printed

class A { { System.out.println(1); } }

class B extends A { { System.out.println(2); } }

class C extends B { { System.out.println(3); } }

public class MainClass { public static void main(String[] args) { C c = new C(); } }

Can someone explain why its printing 1 2 3?

the order of excution in java is static block instance block constructor and any function that is called by an object instance block example { //some code } above block is called instance block

after C class object declaration there is call to its base class that is B and B is also inherited that is derived class if A so class A is called and the first thing is be executed is static block but there is no static block so instance block is executed of class A, B, C respectively in same order as 1 2 3

Leave a Reply Cancel Reply

Name  *

Email  *

Add Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

Post Comment

Scientech Easy logo

Inheritance Example Program in Java for Practice

  • Last Updated On May 17, 2024
  • By Scientech Easy
  • In Core Java Java Interview Programs
  • Read Time 16 mins

In this tutorial, we have listed topic-wise the best collection of inheritance example program in Java with output and explanation.

These inheritance example programs are very important for Java interview purposes and technical test.

If you practice all these interview programs, then definitely, you can able to solve all questions based on Java inheritance . So, let’s start with simple program for practice.

Single Level Inheritance Program in Java

Let’s take a simple example program based on single inheritance in Java. In this example, we will create only one superclass and one subclass that will inherit instance method methodA() from the superclass. Look at the program code to understand better.

Example Program 1:

Explanation:

In this example, we have defined a base class A which contains a single methodA() method. The statement “class B extends A” tells Java compiler that B is a new class inheriting from class A. This makes class A as the base class of class B and class B is known as a derived class.

In subclass B, we have defined one method methodB(). Subclass B contains inherited members ( methodA() ) of base class A and methodB(). In the main method, we have created an object of class B and invoked methods methodA() which is inherited from class A and methodB().

Multilevel Inheritance Program in Java

Let’s take a simple example program based on the multilevel inheritance in Java. Look at the program code and explanation.

Example Program 2:

In this example, we have defined a class X which is a parent class (or base class) for class Y (child class). Class Y is the parent class for class Z (child class).

Thus, class X is the grandfather of class Z (grandchild). The function methodY of class Y is inherited directly from class Y in class Z but the function methodX of class X is inherited indirectly from class X through class Y in class Z.

Hierarchical Inheritance Program in Java

Let’s take a very simple example program in which we will derive multiple subclasses such as B, C, and D from a single superclass A. All subclasses will inherit msgA() method from class A. Look at the program code to understand better.

Example Program 3:

Behavior of Instance Variables in case of Inheritance

We know that instance variables are initialized at compile time. When an instance variable of the superclass is the same as that of the child class instance variable name, the “reference type” plays an important role to access instance variable. Let’s take an example program based on this concept.

[adinserter block=”5″]

Example Program 4:

1. Inside the main() method, an object of class Q has been created. The reference variable q is pointing to the object of class Q.

2. Variable ‘a’ of Q is called because the reference variable for class Q has been created and is pointing to the object of class Q.

3. P p = new Q(); means the superclass reference variable is declared equal to the child class object.

4. Variable ‘a’ of P is called because, in the main() method, the reference variable for class P has been created but the object is created for the child class whereas, the object is referring itself to the superclass.

As the object is referring to the superclass at compile-time, Java compiler checks whether an instance variable is present or not in superclass.

If the instance variable is present in the superclass at the runtime, it will call the instance variable of the superclass.

Behavior of Overriding Method in case of Inheritance

Let’s take an example program to understand the behavior of overriding methods in the case of inheritance.

Example Program 5:

1. Method overriding is only possible in the case of inheritance when the superclass method is overridden in its subclass. In the method overriding, method name, its argument type, the number of arguments, and return type must be the same. [adinserter block=”2″] 2. The variable ‘x’ of Childclass is called because the object is created for the Childclass (subclass). The reference variable obj is pointing to the object of the child class.

3. When statement obj.msg() will be executed by JVM, msg() method of the child class is called because when any overridden method is called, it completely depends on the object through which it is called and the appropriate method call takes place according to this object. Since the object has been created for the child class, so msg() method of the child class will be called, not of a parent class.

4. The statement “Baseclass obj2 = new Childclass()” implies that the superclass reference variable is declared equal to the child class objects. In other words, the superclass reference variable holds the address of the created subclass objects. The reference variable ‘obj2’ is eligible to call only the members of a superclass.

5. When the statement obj2.msg() will be executed by JVM, msg() method of Childclass is called. This is because the object is created for the child class.

6. When obj2.x will be executed by JVM, variable “x” of Baseclass will be called because obj2 is the reference of Baseclass (superclass).

7. The statement obj2.y; an error will occur because variable “y” does not exist in Baseclass.

8. When obj2.msg(); will be executed, msg() of Childclass will be called because the object has been created for Childclass (subclass).

9. On the execution of obj2.msg2();, an error will occur because msg2() is a newly created method in Childclass. Therefore, we cannot access the newly created method by creating the reference of super class and pointing to the object of subclass.

Let’s take another example program based on the behavior of overriding method in case of inheritance.

Example Program 6:

1. Inside the main method,

a. When an object of class Hi will create, the constructor of class Hi will be called immediately. But, the super keyword present in the first line of class Hi will call its parent class Hello. Since the instance block is present in the parent class, it will be executed first before the execution of parent class constructor and calls the show() method.

Since the show() method has been overridden in the child class, therefore, show() method of class Hi will be called. Hence, the output will be “Hi method”.

b. After executing the instance block, the constructor of the parent class will be executed. The output will be “Hello constructor”.

c. Inside the parent class constructor, the show() method of class Hi will be called. So, the output is “Hi method” because the object is created for the child class Hi.

d. After execution of complete parent class constructor, the constructor of Hi (child class) will be called.

2. The show() method of class Hi is called because the object is created for the child class.

3. The output will be the same for lines Hello obj1 = new Hi(); and obj1.show();.

Behavior of Overloaded Method in Inheritance

Method overloading is done at the compile time. Therefore, an appropriate method is invoked according to the reference type to call an overloaded method. Let’s take an example program to clarify this.

Example Program 7:

1. The statement Animal a = new Lion(); implies that ‘a’ is the reference of the parent class whereas an object is created for the child class. When a.food(); is executed, food() method is called through the reference type ‘a’.

At the compile-time, the compiler checks the food() signature in the parent class. If the food() method is not overridden in the child class, it will call the parent class method at runtime. That’s why the output is “What kind of food do lions eat?”.

2. When the line a.food(20); is executed, it will give compile-time error. This is because the parent class Animal does not have a food method that takes an integer argument.

3. When the statement l.food(); will be executed, the food() method of class Lion will be called because the reference variable l is a type of Lion that is a subclass. The food() method of Animal class is available in Lion class through inheritance. Therefore, the output is “What kind of food do lions eat?”.

4. When l.food(20); will be executed, the food(int x) method of class Lion will be called. The output is “Lions eat flesh”.

Key Points:

1. At the compile time, an object reference variable plays an important role to call the method.

2. At runtime, the type of object created plays an important role to call the method.

Scenarios Based Program in Inheritance

Consider the below scenarios.

In this example program, we will create a superclass called AA and one subclass of it, called BB. Superclass AA declares two variables x, y, and two methods named msg1(), and msg2(). The subclass overrides one variable y and one method msg2() declared in AA. It also declares one variable z and one method named msg3().

Example Program 8:

Only change the below class for all types of below scenarios.

Scenario 1:

In this scenario, there is a class Scenario1. Inside the main() method, an object of class AA is created and calls the variables and methods by using the object reference variable.

Scenario 2: 

Scenario 3:

Scenario 4:

Scenario 5:

Scenario 6:

Here, we have covered almost all the variety of inheritance example program in Java with explanations that you must practice before going for the technical interview. All the inheritance program are very important in Java for freshers and experienced level interviews. Keep in mind all the above concepts. Thanks for reading!!!

⇐ Prev Next ⇒

Related Posts

Multiple inheritance in java | example program, top 17 java map interview questions, 35+ top set interview questions in java, 25 top iterator interview questions in java, what is factory method in java with example, recursion in java | example program, command line arguments in java with example, object cloning in java | clone() method, example, trending now.

An example of CSS box model for an HTML element,

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement
  • Java Ternary Operator
  • Java for Loop
  • Java for-each Loop
  • Java while and do...while Loop
  • Java break Statement
  • Java continue Statement
  • Java switch Statement
  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • Java Strings
  • Java Access Modifiers
  • Java this Keyword
  • Java final keyword
  • Java Recursion

Java instanceof Operator

Java OOP(II)

Java inheritance.

Java Method Overriding

Java Abstract Class and Abstract Methods

  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

  • Java File Class
  • Java Reader Class
  • Java Writer Class
  • Java InputStreamReader Class
  • Java OutputStreamWriter Class
  • Java FileReader Class
  • Java FileWriter Class
  • Java BufferedReader
  • Java BufferedWriter Class
  • Java StringReader Class
  • Java StringWriter Class
  • Java PrintWriter Class

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

  • Java enum Inheritance and Interface

Inheritance is one of the key features of OOP that allows us to create a new class from an existing class.

The new class that is created is known as subclass (child or derived class) and the existing class from where the child class is derived is known as superclass (parent or base class).

The extends keyword is used to perform inheritance in Java. For example,

In the above example, the Dog class is created by inheriting the methods and fields from the Animal class.

Here, Dog is the subclass and Animal is the superclass.

Example 1: Java Inheritance

In the above example, we have derived a subclass Dog from superclass Animal . Notice the statements,

Here, labrador is an object of Dog . However, name and eat() are the members of the Animal class.

Since Dog inherits the field and method from Animal , we are able to access the field and method using the object of the Dog .

Subclass Dog can access the field and method of the superclass Animal.

  • is-a relationship

In Java, inheritance is an is-a relationship. That is, we use inheritance only if there exists an is-a relationship between two classes. For example,

  • Car is a Vehicle
  • Orange is a Fruit
  • Surgeon is a Doctor
  • Dog is an Animal

Here, Car can inherit from Vehicle , Orange can inherit from Fruit , and so on.

Method Overriding in Java Inheritance

In Example 1 , we see the object of the subclass can access the method of the superclass.

However, if the same method is present in both the superclass and subclass, what will happen?

In this case, the method in the subclass overrides the method in the superclass. This concept is known as method overriding in Java.

Example 2: Method overriding in Java Inheritance

In the above example, the eat() method is present in both the superclass Animal and the subclass Dog .

Here, we have created an object labrador of Dog .

Now when we call eat() using the object labrador , the method inside Dog is called. This is because the method inside the derived class overrides the method inside the base class.

This is called method overriding. To learn more, visit Java Method Overriding .

Note : We have used the @Override annotation to tell the compiler that we are overriding a method. However, the annotation is not mandatory. To learn more, visit Java Annotations .

super Keyword in Java Inheritance

Previously we saw that the same method in the subclass overrides the method in superclass.

In such a situation, the super keyword is used to call the method of the parent class from the method of the child class.

Example 3: super Keyword in Inheritance

In the above example, the eat() method is present in both the base class Animal and the derived class Dog . Notice the statement,

Here, the super keyword is used to call the eat() method present in the superclass.

We can also use the super keyword to call the constructor of the superclass from the constructor of the subclass. To learn more, visit Java super keyword .

protected Members in Inheritance

In Java, if a class includes protected fields and methods, then these fields and methods are accessible from the subclass of the class.

Example 4: protected Members in Inheritance

In the above example, we have created a class named Animal. The class includes a protected field: name and a method: display() .

We have inherited the Dog class inherits Animal . Notice the statement,

Here, we are able to access the protected field and method of the superclass using the labrador object of the subclass.

  • Why use inheritance?
  • The most important use of inheritance in Java is code reusability. The code that is present in the parent class can be directly used by the child class.
  • Method overriding is also known as runtime polymorphism. Hence, we can achieve Polymorphism in Java with the help of inheritance.
  • Types of inheritance

There are five types of inheritance.

1. Single Inheritance

In single inheritance, a single subclass extends from a single superclass. For example,

Class A inherits from class B.

2. Multilevel Inheritance

In multilevel inheritance, a subclass extends from a superclass and then the same subclass acts as a superclass for another class. For example,

Class B inherits from class A and class C inherits from class B.

3. Hierarchical Inheritance

In hierarchical inheritance, multiple subclasses extend from a single superclass. For example,

Both classes B and C inherit from the single class A.

4. Multiple Inheritance

In multiple inheritance, a single subclass extends from multiple superclasses. For example,

Class C inherits from both classes A and B.

Note : Java doesn't support multiple inheritance. However, we can achieve multiple inheritance using interfaces. To learn more, visit Java implements multiple inheritance .

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance. For example,

Class B and C inherit from a single class A and class D inherits from both the class B and C.

Here, we have combined hierarchical and multiple inheritance to form a hybrid inheritance.

Table of Contents

  • Introduction
  • Example: Java Inheritance
  • Method Overriding Inheritance
  • super Keyword Inheritance
  • protected Members and Inheritance

Sorry about that.

Related Tutorials

Java Tutorial

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Questions and Exercises: Inheritance

1. Consider the following two classes:

a. Which method overrides a method in the superclass? b. Which method hides a method in the superclass? c. What do the other methods do? 2. Consider the Card , Deck , and DisplayDeck classes you wrote in Questions and Exercises: Classes . What Object methods should each of these classes override?

1. Write the implementations for the methods that you answered in question 2.

Check your answers.

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

Java Guides

Java Guides

Search this blog, java inheritance coding questions and answers.

Welcome to the Java Inheritance Coding Quiz. In this quiz, we present 10 coding MCQ questions to test your coding knowledge of Java Inheritance. Each question has a correct and brief explanation.

1. What is the output of the following Java code snippet?

Explanation:.

This is an example of method overriding in Java. The Dog class overrides the sound method of the Animal class. Even though the object is referred to by a variable of type Animal , the Dog 's sound method is called due to polymorphism.

2. What does this Java code snippet output?

Variable shadowing occurs here. The variable i in class B shadows the variable i in class A . Since the reference type of a is A , it accesses A 's i , which is 10.

3. Identify the output of the following code:

The Car constructor calls the superclass constructor Vehicle with arguments, initializing type and maxSpeed . Then it initializes its own field trans .

4. What will be printed by this Java code?

obj1 is an instance of Parent and calls Parent 's show() . obj2 is an instance of Child referred by a Parent reference and calls the overridden show() in Child .

5. What does this code snippet output?

Static methods are not overridden. They are hidden. obj.display() calls the display method of the Base class because the reference type of obj is Base .

6. What is the result of executing this code?

When an instance of a subclass is created, the constructor of the superclass is called first, followed by the constructor of the subclass.

7. What will the following Java code snippet output?

The eat method in Dog class cannot reduce the exception declared in the Animal class. Overridden methods must not throw checked exceptions that are new or broader than those declared by their superclass.

8. What does the following code snippet print?

The display method in class B prints its own field s and then the field s of its superclass A .

9. Determine the output of this Java code:

Class C provides its own implementation of the display method, which overrides the default method in the interface I .

10. What is the result of the following code snippet?

The SubClass provides an implementation for the abstract method of AbstractClass . Both the implemented abstract method and the concrete method are called on the SubClass instance.

11. What is the result of the following code snippet?

The program demonstrates method overloading in Java within the ClassOne . The class defines three overloaded versions of the method function, each accepting a different number of string parameters. In the main method, an instance of ClassOne is created, and the overloaded method is invoked with a single string argument "A," showcasing the flexibility of method overloading in handling different parameter combinations. The output is "AAAAAA," resulting from the concatenation of the provided strings in the invoked methods.

Related Java and Advanced Java Tutorials/Guides

Related quizzes:, post a comment.

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

practice problems on inheritance in java

  • Object Oriented Programming

Java Inheritance I

Using inheritance , one class can acquire the properties of others. Consider the following Animal class:

This class has only one method, walk . Next, we want to create a Bird class that also has a fly method. We do this using extends keyword:

Finally, we can create a Bird object that can both fly and walk .

The above code will print:

This means that a Bird object has all the properties that an Animal object has, as well as some additional unique properties.

The code above is provided for you in your editor. You must add a sing method to the Bird class, then modify the main method accordingly so that the code prints the following lines:

Cookie support is required to access HackerRank

Seems like cookies are disabled on this browser, please enable them to open this website

Java Inheritance Tutorial: explained with examples

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Inheritance is the process of building a new class based on the features of another existing class. It is used heavily in Java, Python, and other object-oriented languages to increase code reusability and simplify program logic into categorical and hierarchical relationships.

However, each language has its own unique way of implementing inheritance that can make switching difficult.

Today, we’ll give you a crash course Java inheritance and show you how to implement the core inheritance tools like typecasting, method overriding, and final entities.

Here’s what we’ll cover today:

What is Inheritance?

  • Inheritance in Java

Java inheritance examples

Advanced concepts to learn next.

Start mastering Java with our hands-on courses today.

Cover

Java Object Class

Java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of (Object Oriented programming system).

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

Inheritance represents the which is also known as a relationship.

(so can be achieved). A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

The 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 a parent or superclass, and the new class is called child or subclass.

. It means that Programmer is a type of Employee.

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

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.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

When a class inherits another class, it is known as a . In the example given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

Output:

When there is a chain of inheritance, it is known as . As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

Output:

When two or more classes inherits a single class, it is known as . In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

File: TestInheritance3.java

Output:

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 the same method and you call it from child class object, there will be ambiguity to call the 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.





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Java Tutorial

Java methods, java classes, java file handling, java how to's, java reference, java examples, java inheritance, java inheritance (subclass and superclass).

In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:

  • subclass (child) - the class that inherits from another class
  • superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class (superclass):

Try it Yourself »

Did you notice the protected modifier in Vehicle?

We set the brand attribute in Vehicle to a protected access modifier . If it was set to private , the Car class would not be able to access it.

Why And When To Use "Inheritance"?

- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

Tip: Also take a look at the next chapter, Polymorphism , which uses inherited methods to perform different tasks.

Advertisement

The final Keyword

If you don't want other classes to inherit from a class, use the final keyword:

If you try to access a final class, Java will generate an error:

The output will be something like this:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Inheritance in Java

Understanding the basics, advantages, and disadvantages of inheritance in java.

Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit properties and behaviors from another class. In our previous article, we discussed classes in Java, which are a blueprint for creating objects with specific properties and behaviors. Now, we will dive deeper into the concept of inheritance and how it allows for the reuse and extension of code.

Before we explore inheritance in depth, it’s important to have a solid understanding of classes and how they work in Java. If you are new to classes, or need some practice problems to hone your skills, we recommend reading our “ Practice Questions  on Class and Objects ” article.

In this article, we will cover the basics of inheritance in Java, including the benefits and drawbacks of inheritance, and how inheritance supports polymorphism. We will also provide some examples of how inheritance can be used in practice, how it differs from composition, and some best practices for using inheritance effectively in your Java code.

So let’s get started!

What is Inheritance?

  • Inheritance is a concept in object-oriented programming that allows one class to inherit properties and behaviors from another class. Think of it like a family tree, where a child inherits certain traits and characteristics from their parent. Similarly, in programming, a child class can inherit properties and behaviors from its parent class. This can save time and effort by reusing existing code and can also help make programs easier to understand and maintain.
  • The class that is being inherited from is called the Super class or Parent class or Base class , while the class that inherits from it is called the subclass or child class or derived class .
  • The subclass can reuse the code and functionality of the superclass, as well as add new methods or override existing ones.
  • To define a subclass in Java, the extends keyword is used followed by the name of the superclass.

In this example, the Trigger class is a subclass of Study and inherits the everytime() method from it. It also has its own unique motivate() method.

“Save the above code as “InheritanceExp”. After saving it, compile and run the code. You will get the below output.

Inheritance promotes code reusability and makes the code more organized and easier to maintain. However, it should be used carefully to avoid creating overly complex class hierarchies and tightly coupled code.

I hope that you can now clearly understand what inheritance is and how to implement it. Let’s take a look at some of the benefits and drawbacks of using inheritance.

Advantages of Inheritance

1. Code reusability : With inheritance, a subclass can inherit methods and properties from its parent class, allowing developers to reuse code without having to rewrite it.

2. Improved code organization : Inheritance can help to organize code by grouping related classes together in a hierarchical structure.

3. Polymorphism : In Java, inheritance enables the use of polymorphism, which allows objects to take on multiple forms. This means that a variable of a parent class type can hold objects of any of its subclasses.

4. Modularity : Inheritance promotes modularity by separating the implementation details of a class from its interface. This allows developers to modify and extend the behavior of a class without affecting the code that uses it.

5. Flexibility and extensibility : Inheritance provides a flexible and extensible way to define new classes by inheriting and modifying existing classes. This allows developers to create new classes that are similar to existing ones, but with additional functionality or customization.

Overall, inheritance is a powerful mechanism in Java that can help to reduce code duplication, improve code organization, promote modularity, and enhance the flexibility and extensibility of software systems.

Disadvantages of Inheritance

Although inheritance provides several benefits in Java, there are also some disadvantages that should be considered when using this mechanism:

1. Tight coupling : Inheritance can result in tight coupling between classes, making the code more complex and difficult to maintain. Changes to the superclass can affect the behavior of all its subclasses, which can lead to unexpected consequences and make it harder to modify or extend the code.

2. Fragile base class problem : The fragile base class problem occurs when changes to the superclass can break the functionality of the subclass. This can be a problem when the superclass is widely used or has many subclasses, as it can require extensive testing and refactoring to ensure that changes to the superclass do not have unintended consequences for its subclasses.

3. Inflexibility : Inheritance can be inflexible when compared to other mechanisms such as composition, which allows for greater flexibility and modularity. Subclasses are limited to the functionality and behavior of their parent class, and changes to the parent class can have a cascading effect on all its subclasses.

4. Overuse : Inheritance can be overused, resulting in overly complex class hierarchies and code that is difficult to understand and maintain. In some cases, composition or other mechanisms may be more appropriate for achieving the desired functionality.

Have you heard about Composition? After reading about inheritance, you may be confused about how inheritance different from composition (containership).

What is Composition?

Composition refers to the practice of combining multiple classes to create more complex objects. In other words, a class can contain an instance of another class as one of its member variables.

For example, consider a car class. The car class can contain instances of other classes such as an engine class, a transmission class, and a steering class, which define the properties and behaviors of those components. By combining these classes through composition, you can create a more complex object that represents a complete car.

Here’s an example of how composition works in Java:

In this example, we define three separate classes for the engine, wheel, and steering wheel components. We then define a Car class that contains instances of these three classes using composition. By using composition in this way, we can create a more modular and maintainable code structure. We can also easily modify or replace any of the components without having to modify the Car class itself.

Difference between Inheritance and Composition

  • Inheritance creates a relationship between classes, while composition creates a relationship between objects.
  • Inheritance is a mechanism for code reuse and creating subtypes of objects, while composition is a mechanism for creating complex objects by combining simpler objects.
  • Inheritance creates a tight coupling between the child class and parent class, while composition creates a looser coupling between the composite object and its parts.
  • Inheritance is a more rigid relationship, as the child class cannot change the behavior of the parent class. Composition allows for more flexibility, as the composite object can be composed of different parts, and the behavior of the composite object can change dynamically.

In conclusion, inheritance and composition are two essential concepts in object-oriented programming that help developers create efficient and flexible software systems. Inheritance allows developers to create new classes that inherit properties and behaviors from existing classes, resulting in more organized and reusable code. Composition, on the other hand, allows developers to create complex objects by combining simpler objects, leading to better code organization and maintenance.

While inheritance has its advantages, such as code reusability and modularity, it also has its disadvantages, such as tight coupling between classes and complex class hierarchies. Composition, on the other hand, offers a more flexible relationship between objects and can lead to better code maintenance.

In our next articles, we will dive deeper into the types of inheritance supported by Java and provide various examples related to it. This will help you gain a more comprehensive understanding of inheritance and how to use it effectively in your software development projects.

' src=

Mahesh Verma

I have been working for 10 years in software developing field. I have designed and developed applications using C#, SQL Server, Web API, AngularJS, Angular, React, Python etc. I love to do work with Python, Machine Learning and to learn all the new technologies also with the expertise to grasp new concepts quickly and utilize the same in a productive manner.

Life Cycle of Data Science

Exploring types of inheritance in java, you may also like, file handling in python – part 1, predict salary on the basis of years of..., how to import  a csv file in python, how to comment out multiple lines in python, creating an analog clock with javascript, what can machine learning be used for, how does machine learning work, predict sales based on advertisement spending, php interview questions and answers – part 1, how to install xampp, leave a comment cancel reply.

Save my name, email, and website in this browser for the next time I comment.

Start a conversation

Important Pages

  • Online Tutor
  • Sample Papers

School & Universities

  • Other Board
  • International Universities

Our Policies

  • Term & Condition
  • Privacy Policy
  • Data Structure

Recent Posts

DZone

  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
  • Manage My Drafts

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

Feeling secure? Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns : Explore key traits of migrating open-source software and its impact on software development.

  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL
  • Twenty Things Every Java Software Architect Should Know
  • Java 8 Threading and Executor Services
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Embracing NoSQL: The Future of Data Storage and Retrieval
  • Books To Start Your Career in Cloud, DevOps, or SRE in 2024
  • MySQL to GBase 8C Migration Guide
  • Optimizing Your Cloud Resources, Part 1: Strategies for Effective Management

Problems With Inheritance in Java

Having trouble with proper subclass inheritance in java click here to figure out how to avoid broken code..

Yogen Rai user avatar

Join the DZone community and get the full member experience.

Inheritance is one of the fundamental principles in an object-oriented paradigm, bringing a lot of values in software design and implementation. However, there are situations where even the correct use of inheritance breaks the implementations. This post is about looking at them closely with examples.

Fragility of Inheritance

The improper design of the parent class can leads subclasses of a superclass to use the superclass in unexpected ways. This often leads to broken code, even when the IS-A criterion is met. This architectural problem is known as the  fragile base class problem in object-oriented programming systems.

The obvious reason for this problem is that the developer of a base class has no idea of the subclass design. When they modify the base class, the subclass implementation could potentially break.

For example, the following program shows how seemingly an inheriting subclass can malfunction by returning the wrong value.

Now, the following shows how to the test to ensure that the inheritance works fine. 

Obviously, if I create the instance of  Square    and call a method  calculateArea , it will give the correct value. But, if I set any of dimension of the  square,  since the square is a rectangle, it gives the unexpected value for the area and the second assertion fails as below:

Is There Any Solution?

There is no straightforward solution to this problem because this is all about following the best practices while designing architecture. According to  Joshua Bloch , in his book  Effective Java , programmers should " design and document for inheritance or else prohibit it ."

If there is a breakable superclass, it is better to prohibit inheritance by labeling a declaration of a class or method, respectively, with the keyword " final. " And, if you are allowing your class to be extended, it is best to only use one way to populate fields.

Here, use either  constructors    or  setters    but not both.

So, if I remove the setters from the parent class as below:

Then, the child classes can't misuse the setter avoiding fragility issue as:

Inheritance Violates Encapsulation

Sometimes, your private data gets modified and violates encapsulation. This will happen if you are extending features from an undocumented parent class — even though the IS-A criterion is met.

For example, let us suppose A overrides all methods in B by first validating input arguments in each method (for security reasons). If a new method is added to B and A   and is not updated, the new method introduces a security hole.

For example, I have created new HashSet implementation to count the numbers of elements added to it as:

Everything looks good. So, it is time to test this extension!

The test fails with a failure in the last assertion as below:

The cause of the problem is that in the implementation of   HashSet, addAll    calls the  add    method. Therefore, we are incrementing  addCount    too many times in calls to   addAll.  

How to Fix This Issue?

The principle is the same as in an earlier fix: " Design and document for inheritance or else prohibit it."  The proper documentation while designing features would reduce the chances of issues like this. 

Fix specific to this issue is not to increment   addCount    in   addAll    operations, since the value is getting updated in  add    operation, which gets called from   addAll     as:

So, this is it! Until next time, happy learning!

As usual, all the source code presented in the above examples is available on GitHub .

Opinions expressed by DZone contributors are their own.

Partner Resources

  • About DZone
  • Send feedback
  • Community research
  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone
  • Terms of Service
  • Privacy Policy
  • 3343 Perimeter Hill Drive
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

inheritance-examples

Here are 33 public repositories matching this topic..., madahetooo / javalanguagefullproject.

This is a Full Project contains Almost the java programming language concepts

  • Updated Nov 21, 2020

refactorinqq / BridgeBase

Base bridge for Minecraft clients

  • Updated Dec 31, 2023

ashcode028 / Zotato

Food Delivery App Low-Level Implementation

  • Updated Nov 10, 2021

harunpetekkaya21 / JavaOOP

  • Updated Jan 22, 2019

ShubhamRandive1 / JavaAssignments

Java * assignments which includes the topics of core java : OOPS(object oriented programming) ,inheritance,multithreading, encryption and decrypption, encapsulation and etc

  • Updated Sep 4, 2022

abhipatel35 / Java

Explore Java from basics to Object-Oriented Programming (OOP) concepts with practical examples and detailed explanations. Dive into approximately 55-60 Java programs covering topics like variables, control flow, arrays, OOP principles, exception handling, and more. Ideal for learners looking to solidify their understanding of Java fundamentals.

  • Updated Feb 12, 2024

Raghavjajooc123 / OOPS

Object Oriented Programming - A practice repository for my OOP practice in Java.

  • Updated Jun 2, 2022

yashlad27 / JavaProjects

Java Projects and Assignments which I did as I had started my Java Development Journey.

  • Updated Apr 23, 2022

manishjayadevadiga / C2TC_corejava

Contains all the Day-to-day projects created during TNSIF C2TC

  • Updated Oct 16, 2023

mypage-solutions / Lesson_12

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

  • Updated Feb 14, 2022

Favour-Madubuko / Object_oriented_programming

This repository contains Object Oriented Programming Principles and how to model their relationships with examples

  • Updated Aug 6, 2023

juannaee / Projeto-Java

Praticando linguagem Java. Nesse exemplo fiz um sistema de calculos com logicas de polimorfismo, herença e classe/metodos abstratos.

  • Updated Jan 30, 2023

smoothiesusie / vending-machine

You're developing an application for the newest vending machine distributor, Umbrella Corp. They've released a new vending machine, Vendo-Matic 800, that's integrated with everyone's bank accounts, allowing customers to purchase products from their computers for their convenience.

  • Updated Dec 21, 2023

VaishnaviThakre / Java-Programs

This repository contains codes of java

  • Updated Jun 5, 2024

ChristianHundahl / Softwareudvikling_07_04_2021_Inheritance_Files

Assignment on Inheritance and Files using examples.

  • Updated May 6, 2021

bell-kevin / inheritanceExample

inheritance Example

  • Updated Aug 26, 2022

elcnec / Polymorphism-in-java

Example for Polymorphism

  • Updated Sep 20, 2022

rikhitha / java-srm

  • Updated Jul 14, 2021

thrisler261 / Inheritance_with_JUnit_Interface

A biger Projekt about Inheritance with Junit tests and Interface implementation, Exeptions and FileIO

  • Updated Dec 23, 2022

Improve this page

Add a description, image, and links to the inheritance-examples topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the inheritance-examples topic, visit your repo's landing page and select "manage topics."

Problems with Inheritance in Java

Inheritance problems in Java | Limitations of Inheritance | In this post, we will see problems with Inheritance in Java and how to solve them?

Limitations of inheritance in Java

Multiple Inheritance Problem

Problem :- If we want the functionalities of multiple classes then we have to use multiple inheritances but Java doesn’t support multiple inheritances through classes.

Solution :- We can bring the effect of multiple inheritances through composition.

Fragile Base Class Problem

With inheritance, code becomes fragile (easily breakable). This fragile base class problem is a very well-known architectural problem in object-oriented programming systems, where base classes (superclasses) are considered “fragile” because seemingly safe modifications to a base class, when inherited by the derived classes, may cause the derived classes to malfunction. The programmer cannot determine whether a base class change is safe simply by examining in isolation the methods of the base class.

One possible solution is to make instance variables private to their defining class and force subclasses to use accessors to modify superclass states. These changes prevent subclasses from relying on implementation details of superclasses and allow subclasses to expose only those superclass methods that are applicable to themselves.

Another alternative solution could be to have an interface instead of the superclass. Let us understand it through an example:-

If the methods of java.lang.Object class is disturbed then the entire Java class hierarchy will be collapsed.

It was one simple example where we get the problem, and there can multiple different examples where code becomes fragile. In the book Effective Java, author Joshua Bloch writes that programmers should “ Design and document for inheritance or else prohibit it “.

Complexity in Testing

With inheritance, code testing is a bit complex/heavy process and increases the burden to programmers. Testing means checking actual results with expected results. If matched then the result is positive else the result is negative. Programmer testing on his own piece of code is called unit testing. We perform unit testing either manually or by taking the support of different tools like JUnit.

While testing subclass, we need to perform testing not only on the direct methods of the subclass, we have to perform unit testing also on the inheritance methods of other classes that are there in the inheritance classes.

Here we need to do unit testing only on B class methods, not on the A-class methods i.e. only m3() and m4() methods should be tested. This reduces the burden to programmers. By the way, m1() and m2() methods are called internally from m3() and m4() methods therefore they also will be tested in that process.

Apart from these problems sometimes we need to add functionalities to the existing object. Always adding new functionalities/responsibilities on the existing object through inheritance is bad practice and we may end up getting a huge number of classes. We will discuss this problem and solution in detail in the Decorator/Wrapper design pattern .

Leave a Comment Cancel Reply

practice problems on inheritance in java

  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Crack System Design Round
  • System Design Bootcamp
  • System Design Interview Questions
  • Microservices
  • Scalability

Memento Design Pattern in Java

The Memento design pattern in Java is a behavioral design pattern used to capture and restore the internal state of an object without exposing its implementation details.

Important Topics for Memento Design Pattern in Java

What is the Memento Design Pattern in Java?

Components of memento design pattern in java, communication between the components, real-world analogy of memento design pattern in java, memento design pattern example in java, when to use memento design pattern in java, when not to use memento design pattern in java.

The Memento design pattern in Java is a behavioral pattern that is used to capture and restore an object’s internal state without violating encapsulation. It allows you to save and restore the state of an object to a previous state, providing the ability to undo or roll back changes made to the object.

  • As your application progresses, you may want to save checkpoints in your application and restore them to those checkpoints later.
  • The intent of the Memento Design pattern is without violating encapsulation, to capture and externalize an object’s internal state so that the object can be restored to this state later.

Below are the components of the Memento Design Pattern in Java:

1. Originator

This component is responsible for creating and managing the state of an object. It has methods to set and get the object’s state, and it can create Memento objects to store its state. The Originator communicates directly with the Memento to create snapshots of its state and to restore its state from a snapshot.

The Memento is an object that stores the state of the Originator at a particular point in time. It only provides a way to retrieve the state, without allowing direct modification. This ensures that the state remains

3. Caretaker

The Caretaker is responsible for keeping track of Memento objects. It doesn’t know the details of the state stored in the Memento but can request Mementos from the Originator to save or restore the object’s state.

Typically represented as the part of the application or system that interacts with the Originator and Caretaker to achieve specific functionality. The client initiates requests to save or restore the state of the Originator through the Caretaker.

Communication-between-components-(1)

  • Client : The client initiates the process by requesting the Originator to perform some operation that may modify its state or require the state to be saved. For example, the client might trigger an action like “save state” or “restore state.”
  • The Originator creates a Memento object that captures its current state.
  • It returns the Memento to the client or Caretaker for storage.
  • The Originator retrieves the desired Memento containing the state it wants to restore.
  • It restores its state using the state stored in the Memento.
  • The Caretaker receives the Memento from the Originator.
  • It stores the Memento for future use.
  • The Caretaker retrieves the appropriate Memento from its storage.
  • It provides the Memento to the Originator for state restoration.

2-(1)

  • The caretaker calls the createMemento() method on the originator asking the originator to pass it a memento object.
  • At this point the originator creates a memento object saving its internal state and passes the memento to the caretaker.
  • The caretaker maintains the memento object and performs the operation. In case of the need to undo the operation, the caretaker calls the setMemento() method on the originator passing the maintained memento object.
  • The originator would accept the memento, using it to restore its previous state.

Imagine you’re an artist painting a picture (Originator). You have a beautiful painting that you’ve been working on, and you want to make sure you can save its progress and go back to previous versions if needed.

  • You, the artist, represent the Originator.
  • You’re responsible for creating and managing the state of your painting (object).
  • As you work on your painting, you can create snapshots or “Mementos” of its current state.
  • A Memento in this analogy could be likened to a photograph of your painting at a specific point in time.
  • Just like taking a picture captures the appearance of your painting at that moment, a Memento captures the state of your painting.
  • You could take a photograph of your painting at various stages of completion to have snapshots of its progress.
  • The Caretaker is like an art collector who helps you manage your paintings and their snapshots.
  • They don’t paint the pictures themselves (like the Originator), but they’re responsible for keeping track of the snapshots (Mementos) and ensuring they’re stored safely.
  • They might label each photograph with a date or description to help you remember which stage of the painting it represents.
  • When you want to revisit an earlier version of your painting, you ask the art collector (Caretaker) to retrieve the corresponding photograph (Memento) for you to study or restore.

So, in this analogy, you, the artist, create and manage your painting (Originator), take photographs to capture its progress (Memento), and rely on an art collector (Caretaker) to organize and store those photographs for future reference or restoration. This illustrates how the components of the Memento pattern work together in a real-life scenario.

Imagine you’re building a text editor application, and you want to implement an undo feature that allows users to revert changes made to a document. The challenge is to store the state of the document at various points in time and restore it when needed without exposing the internal implementation of the document.

Benefit of Using Memento Pattern in this scenario:

Using the Memento pattern in this scenario provides several benefits:

  • Encapsulation : The Memento pattern allows you to encapsulate the state of the document within Memento objects, preventing direct access and manipulation of the document’s state.
  • Undo Functionality: By storing snapshots of the document’s state at different points in time, the Memento pattern enables the implementation of an undo feature, allowing users to revert changes and restore previous document states.
  • Separation of Concerns: The Memento pattern separates the responsibility of state management from the document itself, promoting cleaner and more maintainable code.

1-(1)

Below is the code of above problem statement using Interpreter Pattern in Java:

Let’s break down into the component wise code:

1. Originator (Document)

3. caretaker (history), complete code for the above example in java.

Below is the complete code for the above example in Java:

  • Undo functionality : When you need to implement an undo feature in your application that allows users to revert changes made to an object’s state.
  • Snapshotting : When you need to save the state of an object at various points in time to support features like versioning or checkpoints.
  • Transaction rollback : When you need to rollback changes to an object’s state in case of errors or exceptions, such as in database transactions.
  • Caching : When you want to cache the state of an object to improve performance or reduce redundant computations.
  • Large object state : If the object’s state is large or complex, storing and managing multiple snapshots of its state can consume a significant amount of memory and processing resources.
  • Frequent state changes : If the object’s state changes frequently and unpredictably, storing and managing snapshots of its state may become impractical or inefficient.
  • Immutable objects : If the object’s state is immutable or easily reconstructible, there may be little benefit in using the Memento pattern to capture and restore its state.
  • Overhead : Introducing the Memento pattern can add complexity to the codebase, especially if the application does not require features like undo functionality or state rollback.

Please Login to comment...

Similar reads.

  • Java Design Patterns
  • Design Pattern
  • System Design

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Quiz & Worksheet

    practice problems on inheritance in java

  2. Inheritance in Java

    practice problems on inheritance in java

  3. Single Inheritance In Java With Examples

    practice problems on inheritance in java

  4. Inheritance in Java with Example

    practice problems on inheritance in java

  5. Java Inheritance (With Examples)

    practice problems on inheritance in java

  6. Inheritance in Java

    practice problems on inheritance in java

VIDEO

  1. Implementing multiple inheritance #java #coding #javadeveloper

  2. Inheritance practice set Solution

  3. Java Inheritance

  4. Master Java Inheritance FAST! [Inheritance in Java] #shorts #short #ytshorts #java

  5. #15 Understanding Inheritance in Java Implementing Multi-Level Inheritance

  6. Java Inheritance

COMMENTS

  1. Java Inheritance: Exercises, Practice, Solution

    6. Write a Java program to create a class called Animal with a method named move (). Create a subclass called Cheetah that overrides the move () method to run. Click me to see the solution. 7. Write a Java program to create a class known as Person with methods called getFirstName () and getLastName ().

  2. Java Inheritance Quiz Practice Coding Questions

    Java Practice Coding Questions 88 Comments In this post, there are some 40 Java inheritance quiz type questions and answers which will help you to understand Java inheritance concept better.

  3. Java Inheritance

    Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features (fields and methods) of another class. So we can make object of a class cls2, which can use both mul and add methods. Main function is already created in the editor and instance of cls2 is also ...

  4. Inheritance Example Program in Java for Practice

    In this example, we will create only one superclass and one subclass that will inherit instance method methodA () from the superclass. Look at the program code to understand better. Example Program 1: package inheritancePractice; // Create a base class or superclass. public class A.

  5. Java Inheritance (With Examples)

    In Java, inheritance is an is-a relationship. That is, we use inheritance only if there exists an is-a relationship between two classes. For example, Car is a Vehicle. Orange is a Fruit. Surgeon is a Doctor. Dog is an Animal. Here, Car can inherit from Vehicle, Orange can inherit from Fruit, and so on.

  6. Practice Problems on Inheritance in Java

    Welcome to the article on "Practice Problems on Inheritance in Java". Inheritance is a powerful concept in object-oriented programming, and it is important to understand its various aspects and applications. If you want to learn more about inheritance, please refer to our previous article titled "Inheritance in Java".

  7. Quiz about Java Inheritance

    1) In Java all classes inherit from the Object class directly or indirectly. The Object class is root of all classes. 2) Multiple inheritance is not allowed in Java. 3) Unlike C++, there is nothing like type of inheritance in Java where we can specify whether the inheritance is protected, public or private.

  8. Questions and Exercises: Inheritance (The Java™ Tutorials > Learning

    The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.

  9. Java Tutorial: Exercise & Practice Questions on Inheritance

    Chapter 10 Inheritance: Practice Set - In this video we will solve some of the important practice questions on inheritance and object oriented programming in...

  10. Java Inheritance Quiz

    Welcome to Java Inheritance Quiz!. This Java Inheritance Quiz consists of important 20 multiple-choice questions (MCQ) with answers and explanations. Go ahead and test your knowledge of the Java Inheritance concept. The first 10 questions are very simple and the remaining 10 questions are medium and complex. 1.

  11. Inheritance in Java

    It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields of that class. In addition, you can add new fields and methods to your current ...

  12. Java Inheritance Coding Questions and Answers

    Welcome to the Java Inheritance Coding Quiz. In this quiz, we present 10 coding MCQ questions to test your coding knowledge of Java Inheritance. Each question has a correct and brief explanation. 1. What is the output of the following Java code snippet? String sound() {. return "Generic Sound" ; class Dog extends Animal {. String sound() {.

  13. Java Inheritance I

    Java Inheritance I. Using inheritance, one class can acquire the properties of others. Consider the following Animal class: This class has only one method, walk. Next, we want to create a Bird class that also has a fly method. We do this using extends keyword: Finally, we can create a Bird object that can both fly and walk.

  14. Java Inheritance Tutorial: explained with examples

    Inheritance is the process of building a new class based on the features of another existing class. It is used heavily in Java, Python, and other object-oriented languages to increase code reusability and simplify program logic into categorical and hierarchical relationships. However, each language has its own unique way of implementing ...

  15. PDF Practice Problems: Inheritance & Polymorphism

    Practice Problems: Inheritance & Polymorphism public class Foo { public void method1() { System.out.println("foo 1"); } public void method2() { ... So Java uses the toString method defined in class D, which returns the values of x, y, and z within class D (or "DxAyDz"). Notice the difference between how fields get handled, and

  16. Inheritance in Java

    Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).. 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 the parent class.

  17. Java Inheritance (Subclass and Superclass)

    In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class. superclass (parent) - the class being inherited from. To inherit from a class, use the extends keyword.

  18. Inheritance in Java

    If you are new to classes, or need some practice problems to hone your skills, we recommend reading our "Practice Questions on Class and Objects" article. In this article, we will cover the basics of inheritance in Java, including the benefits and drawbacks of inheritance, and how inheritance supports polymorphism.

  19. Problems With Inheritance in Java

    java.lang.AssertionError: New number of attempted adds so far Expected :6 Actual :9 Inheritance The cause of the problem is that in the implementation of HashSet, addAll calls the add method.

  20. Practice Problem

    In today's video we are going learn how to solve the school practice problem - Remove Spaces.Problem Link: https://practice.geeksforgeeks.org/problems/java-h...

  21. 40 Java Inheritance Practice Coding Questions

    40 Java Inheritance Practice Coding Questions - Free download as Word Doc (.doc / .docx), PDF File (.pdf), Text File (.txt) or read online for free. This document contains 40 practice coding questions related to Java inheritance. The questions cover topics like extending multiple classes, overriding methods, calling superclass constructors, accessing private members of superclasses, and more.

  22. inheritance-examples · GitHub Topics · GitHub

    encapsulation java-basic-code-practice inheritance-examples access-modifiers polymorphism-and-abstraction overloading-overriding Updated Oct 16, 2023; Java; mypage-solutions / Lesson_12 Star 1. Code Issues Pull requests Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. ...

  23. Problems with Inheritance in Java

    Java doesn't support multiple inheritances through classes. public class A { } public class B { } Problem :- If we want the functionalities of multiple classes then we have to use multiple inheritances but Java doesn't support multiple inheritances through classes. // Invalid statement public class C extends A, B { }

  24. Differences between Interface and Class in Java

    5. Inheritance: Class: Supports single inheritance (a class can inherit from one superclass only). Interface: Supports multiple inheritance (a class can implement multiple interfaces, and an interface can extend multiple interfaces). 6. Constructors: Class: Can have constructors to initialize the object. Interface: Cannot have constructors. 7 ...

  25. Memento Design Pattern in Java

    When to use Memento Design Pattern in Java. Undo functionality: When you need to implement an undo feature in your application that allows users to revert changes made to an object's state.; Snapshotting: When you need to save the state of an object at various points in time to support features like versioning or checkpoints.; Transaction rollback: When you need to rollback changes to an ...