0% found this document useful (0 votes)
43 views8 pages

Java Inheritance Quiz Questions

Uploaded by

mostafa nasser
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views8 pages

Java Inheritance Quiz Questions

Uploaded by

mostafa nasser
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Inheritance Trending in News View More

105 Funny Things to Do to Make


Question 1 Someone Laugh
Best PS5 SSDs in 2024: Top Picks for
Expanding Your Storage
Which of the following is true about inheritance in Java?
Best Nintendo Switch Controllers in
2024
1) Private methods are final. #geekstreak2024 – 21 Days POTD
2) Protected members are accessible within a package and Challenge Powered By Deutsche Bank
inherited classes outside the package. Full Stack Developer Roadmap [2024
3) Protected methods are final. Updated]
4) We cannot override private methods.

1, 2 and 4

Only 1 and 2

1, 2 and 3

2, 3 and 4

Discuss it

Question 1 ‒ Explanation
See [Link] and htt
p://[Link]/comparison-of-inheritance-in-c-and-java/

Question 2

Output of following Java program?

Java

class Base {
public void Print() {
[Link]("Base");
}
}

class Derived extends Base {


public void Print() {
[Link]("Derived");
}
}

class Main{
public static void DoPrint( Base o ) {
[Link]();
}
public static void main(String[] args) {
Base x = new Base();
Base y = new Derived();
Derived z = new Derived();
DoPrint(x);
DoPrint(y);
DoPrint(z);
}
}

Base
Derived
Derived

Base
Base
Derived

Base
Derived
Base

Compiler Error

Discuss it

Question 2 ‒ Explanation
See question 1 of
[Link]

Question 3

Predict the output of following program. Note that fun() is public in base and
private in derived.

Java

class Base {
public void foo() { [Link]("Base"); }
}

class Derived extends Base {


private void foo() { [Link]("Derived"); }
}

public class Main {


public static void main(String args[]) {
Base b = new Derived();
[Link]();
}
}

Base

Derived

Compiler Error

Runtime Error

Discuss it
Question 3 ‒ Explanation
It is compiler error to give more restrictive access to a derived class function w
hich overrides a base class function.

Question 4

Predict the output of following Java Program

Java

// filename [Link]
class Grandparent {
public void Print() {
[Link]("Grandparent\'s Print()");
}
}

class Parent extends Grandparent {


public void Print() {
[Link]("Parent\'s Print()");
}
}

class Child extends Parent {


public void Print() {
[Link]();
[Link]("Child\'s Print()");
}
}

public class Main {


public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}

Compiler Error in [Link]()

Grandparent\'s Print()
Parent\'s Print()
Child\'s Print()

Runtime Error

Discuss it

Question 4 ‒ Explanation
In Java, it is not allowed to do [Link]. We can only access Grandparent\'s
members using Parent. For example, the following program works fine.

// Guess the output


// filename [Link]
class Grandparent {
public void Print() {
[Link]("Grandparent\'s Print()");
}
}
class Parent extends Grandparent {
public void Print() {
[Link]();
[Link]("Parent\'s Print()");
}
}

class Child extends Parent {


public void Print() {
[Link]();
[Link]("Child\'s Print()");
}
}

class Main {
public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}

Question 5

Output of following Java Program?

Java

class Base {
public void show() {
[Link]("Base::show() called");
}
}

class Derived extends Base {


public void show() {
[Link]("Derived::show() called");
}
}

public class Main {


public static void main(String[] args) {
Base b = new Derived();;
[Link]();
}
}

Derived::show() called

Base::show() called

Discuss it

Question 5 ‒ Explanation
In the above program, b is a reference of Base type and refers to an abject of De
rived class. In Java, functions are virtual by default. So the run time polymorph
ism happens and derived fun() is called.

Question 6

Which of the following is true about inheritance in Java. 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.

1, 2 and 3

1 and 2

2 and 3

1 and 3

Discuss it

Question 6 ‒ Explanation
See Comparison of Inheritance in C++ and Java

Question 7

final class Complex {

private final double re;


private final double im;

public Complex(double re, double im) {


[Link] = re;
[Link] = im;
}

public String toString() {


return "(" + re + " + " + im + "i)";
}
}

class Main {
public static void main(String args[])
{
Complex c = new Complex(10, 15);
[Link]("Complex number is " + c);
}
}

Complex number is (10.0 + 15.0i)


Compiler Error

Complex number is SOME_GARBAGE

Complex number is Complex@8e2fb5


Here 8e2fb5 is hash code of c

Discuss it

Question 7 ‒ Explanation
See [Link]

Question 8

Java

class Base {
final public void show() {
[Link]("Base::show() called");
}
}

class Derived extends Base {


public void show() {
[Link]("Derived::show() called");
}
}

class Main {
public static void main(String[] args) {
Base b = new Derived();;
[Link]();
}
}

Base::show() called

Derived::show() called

Compiler Error

Runtime Error

Discuss it

Question 8 ‒ Explanation
Final methods cannot be overridden. See the compiler error
here
.

Question 9
\Java\

class Base {
public static void show() {
[Link]("Base::show() called");
}
}

class Derived extends Base {


public static void show() {
[Link]("Derived::show() called");
}
}

class Main {
public static void main(String[] args) {
Base b = new Derived();
[Link]();
}
}

Base::show() called

Derived::show() called

Compiler Error

Discuss it

Question 9 ‒ Explanation
Like C++, when a function is static, runtime polymorphism doesn\'t happen.

You have completed 9/9 questions .


Your accuracy is 55%.

Last Updated : Mar 22, 2024

Take a part in the ongoing discussion View All Discussion


Company Languages DSA Data Web Python
About Us Python Data Science & Technologies Tutorial
Corporate & Communications Legal Java Structures
Address:- A-143, 9th Floor, In Media
ML HTML Python
C++ Algorithms CSS Programming
Sovereign Corporate Tower, Data Science
Sector- 136, Noida, Uttar Contact Us PHP DSA for JavaScript Examples
With Python
Pradesh (201305) | Registered Advertise with GoLang Beginners TypeScript Python Projects
Address:- K 061, Tower K, Data Science
us SQL Basic DSA ReactJS Python Tkinter
Gulshan Vivante Apartment, For Beginner
GFG Corporate R Language Problems NextJS Web Scraping
Sector 137, Noida, Gautam Solution
Machine
Buddh Nagar, Uttar Pradesh, Android DSA Bootstrap OpenCV Tutorial
Learning
201305 Placement Tutorial Roadmap Web Design Python Interview
ML Maths
Training Tutorials Top 100 Question
Data
Program Archive DSA Django
Visualisation
GeeksforGeeks Interview
Pandas
Community Problems
NumPy
DSA
NLP
Roadmap
Deep Learning
by
Sandeep
Jain
All Cheat
Sheets

Computer DevOps System Inteview School GeeksforGeeks


Science Git Design Preparation Subjects Videos
Operating Linux High Level Competitive Mathematics DSA
Systems AWS Design Programming Physics Python
Computer Docker Low Level Top DS or Algo Chemistry Java
Network Kubernetes Design for CP Biology C++
Database Azure UML Company-Wise Social Science Web Development
Management GCP Diagrams Recruitment English Data Science
System DevOps Interview Process Grammar CS Subjects
Software Roadmap Guide Company-Wise Commerce
Engineering Design Preparation World GK
Digital Logic Patterns Aptitude
Design OOAD Preparation
Engineering System Puzzles
Maths Design
Software Bootcamp
Development Interview
Software Questions
Testing

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

Common questions

Powered by AI

Inheritance in Java differs from C++ in several key aspects. All Java classes, except the primitive types, implicitly inherit from the Object class directly or indirectly, making Object the root of the inheritance hierarchy, a concept absent in C++. Additionally, Java does not support multiple inheritance directly as C++ does through class hierarchies. Java circumvents this limitation by allowing the implementation of multiple interfaces, thereby achieving some level of code reusability while avoiding the complexity of multiple inheritance . Furthermore, unlike C++, Java does not allow specifying the type of inheritance (public, protected, private), rather it uses access modifiers within classes to achieve controlled access .

The 'final' keyword in Java, when applied to methods, indicates that the method cannot be overridden by subclasses. This enforces non-mutable behavior in method functionality, preserving the integrity of the method implementation as defined in the superclass. This is particularly useful when a method is critical to the class’s operation and should not be modified by subclasses, ensuring consistency and reliability in the method's behavior across different classes . If a subclass attempts to override a final method, it results in a compile-time error .

Private methods in a Java class are not visible to subclasses and are implicitly final since they are not accessible outside the class they are defined in. As a result, they cannot be overridden because method overriding necessitates visibility of the superclass method to allow polymorphic behavior. This means that private methods do not partake in the inheritance model directly and are confined to the internal implementation of the class, thus preserving encapsulation .

In Java, polymorphism allows methods to have the same name but behave differently based on the object that invokes them. This concept is especially vital in method overriding, where a method in a subclass has the same name and signature as a method in the parent class, and the subclass method is executed based on the runtime object type. Java achieves this through virtual functions, and by default, all non-static methods in Java are virtual . For instance, if a base class reference points to a derived class object and a method is called on this reference, the derived class's method will be executed demonstrating runtime polymorphism .

Java does not support multiple inheritance with classes to avoid problems such as the diamond problem found in languages like C++. This prevents ambiguity arising from inheriting the same method from multiple parent classes. Instead, Java uses interfaces to achieve a form of multiple inheritance. Interfaces allow a class to inherit method signatures from multiple sources while avoiding the complexity and ambiguity that multiple concrete inheritances would introduce. Although interfaces do not provide a method implementation, they allow classes to implement the methods they declare, facilitating flexible and reusable code design .

Java provides several access modifiers—public, protected, no modifier (package-private), and private. These access levels control visibility across different scopes. Public members are accessible everywhere, while protected members are accessible within the same package or by subclassing in another package. Package-private, the default access with no modifier, confines access to within the same package, while private limits access to within the class itself . The protected modifier is particularly significant as it strikes a balance between subclass access and package visibility, enhancing controlled inheritance .

The 'super' keyword in Java serves as a reference to the superclass of the current object. It is primarily used to invoke superclass methods and constructors. When used with methods, 'super' can call a method from the parent class that is overridden in the subclass, essentially accessing superclass functionality from within a subclass. When used in constructors, it enables the invocation of a superclass's constructor, allowing for the initialization of inherited class fields before the subclass adds its enhancements. This ensures proper initialization in inheritance hierarchies .

Static methods in Java are associated with the class rather than any instance of the class, meaning they are shared across all instances. They are not subject to runtime polymorphism since they are resolved at compile-time. Consequently, static methods cannot be overridden in the traditional sense, though they can be hidden by another static method of the same name in subclass. When a static method is called, its implementation is determined by the class reference type directly rather than the runtime type of the object. This means static methods do not participate in inheritance in the same manner as non-static methods .

Abstract classes in Java provide a way to create classes that cannot be instantiated on their own, serving as a blueprint for subclasses. They can contain both abstract methods (without implementation) and concrete methods (with implementation). This makes them suitable when some shared functionality should be implemented once and shared among subclasses. In contrast, interfaces in Java, prior to Java 8, could only declare methods. However, since Java 8, interfaces can have default and static methods with implementation, closing the gap with abstract classes. Nonetheless, abstract classes can extend only one other class, while interfaces can support multiple inheritances, making interfaces more versatile for achieving polymorphic behavior across diverse hierarchies .

Given a Java class setup where a subclass tries to hide a method of a superclass using a private method, compilation errors occur. If a subclass declares a method with the same name as in the superclass but more restrictive access, such as using private, the Java compiler throws an error since access privileges cannot be tightened in the subclass . Java's compilation prevents such illegal method overriding attempts, preserving the polymorphic contract and ensuring that the declared methods in superclass are accessible with at least the same level of access in subclasses.

You might also like