Loading...
Loading...
Java interview guide
Classes, inheritance, polymorphism, abstraction, interfaces and encapsulation. Every answer is short enough to say aloud, and every question links to the lesson that teaches it.
60 questionsLast updated
The child's constructor may use parent fields or methods. If the parent part were built later, the child would see unset values. Building from the top down means every level can trust the levels above it.
Lesson: Constructor order in inheritanceNo. final on a class only stops other classes from extending it. Its normal fields can still change; to lock a field, the field itself must be final.
Then nobody could reuse it with inheritance. A final class suits a complete, sensitive class like String. For a class that is meant to be a parent, like Account, I would keep the class open and make only the critical methods final.
super(message) in the constructor?The message is stored by the parent class, Exception. super(message) passes it up, and the inherited getMessage() returns it later. Without it, getMessage() returns null.
It removes copied code, keeps common rules in one place and shows IS-A relationships clearly. The risk is tight coupling: a change in the parent reaches every child, so a bad parent design spreads everywhere.
Lesson: Common mistakes and practiceNo. It fits only when the IS-A test passes. If a class just needs another class's features, like a car needing an engine, a field (HAS-A) is better. The Composition & Relationships module covers that.
Lesson: Common mistakes and practiceCompile-time (static) polymorphism is method overloading: the compiler picks the method from the arguments. Runtime (dynamic) polymorphism is method overriding: the JVM picks the child's version from the actual object while the program runs.
Lesson: What is polymorphism?if (type.equals("UPI")) ... else if (type.equals("CARD")) ...?Every new type means editing the chain, often in several places, and a forgotten branch fails silently in the else. With polymorphism each class carries its own behaviour, so the calling code never changes when a type is added.
No. A private method is not inherited, so the child cannot see it. If the child writes a method with the same name, it is a completely new method, and the parent's own code still calls its private version.
It can throw any unchecked exception. It cannot throw a new or broader checked exception, because code calling the parent method is not prepared to catch it; javac says "overridden method does not throw Exception". It may throw fewer or narrower checked exceptions.
Lesson: Method overriding and its rules@Override mandatory? What happens if you leave it out?It is not mandatory; a correct override works without it. But if I make a mistake, Java quietly treats my method as a new one and the parent version keeps running. That is why I always write it.
Lesson: The @Override annotation@Override affect the program at run time?No. It is checked only by javac at compile time. The running program behaves exactly the same with or without it.
super.method() inside an override?The plain name means the child version, so the method calls itself again and again. The stack fills up and the program crashes with java.lang.StackOverflowError.
I would override bonus(int salary) in Manager and return super.bonus(salary) + 5000. The normal rule then lives only in Employee, and the manager's rule adds just the extra part.
static, private or final method be overloaded? Can it be overridden?All three can be overloaded, because overloading only needs different parameters. None can be overridden: static methods belong to the class, private methods are not inherited and final methods are locked.
Lesson: Overloading vs overridingUpcasting is storing a child object in a parent-type variable, like Payment p = new UpiPayment();. It is automatic and always safe, because every UpiPayment is a Payment. The object itself stays a UpiPayment.
Payment p = new UpiPayment(); instead of UpiPayment p = new UpiPayment();?Code written against the parent type works with every payment type. If I later switch to a CardPayment, I change only the new part; the rest of the code, which calls p.pay(), stays the same.
It is how Java decides at run time which overridden method to call. When a method is called through a parent reference, the JVM looks at the actual object and runs that class's version. This is how runtime polymorphism works.
Lesson: Dynamic method dispatchParent p = new Child(); p.info(); where info() is static in both. What runs?Parent.info(). Static methods are not dispatched by the object; the reference type decides. That is method hiding, which is why static methods should be called with the class name.
Polymorphism is the idea: one call, many forms. Overloading gives the compile-time kind, where javac picks by arguments. Overriding gives the runtime kind, and dynamic method dispatch is the JVM mechanism that picks the overriding version from the object.
Lesson: Common mistakes and practice@Override with super.method() such a common pair in real code?@Override proves the method really replaces the parent's, and super.method() keeps the parent's work instead of copying it. Together they let a child add one small step while the shared logic stays in one place.
Encapsulation hides data: fields are private and change only through methods that check the values. Abstraction hides details and steps: callers see only the actions they need. An ATM class does both: balance is private (encapsulation) and one withdraw method hides the PIN and balance checks (abstraction).
Yes. If every field is private but the caller must call five public steps in the right order, the data is protected but the details leak out. A better design hides those steps behind one method like book(name, seats), so the caller cannot get the order wrong.
A concrete class is a normal class: every method has a body, so we can create objects of it with new. An abstract class cannot be instantiated and may leave some methods abstract. Usually the abstract class is the parent and the concrete classes are its children.
private, static or final? Can a class be abstract and final?No to all of them. An abstract method must be overridden by a child, but a private method is not visible to it, a static one is not overridden and a final one cannot be. A class cannot be abstract and final either, because one needs children and the other forbids them; javac reports illegal combination of modifiers.
A concrete method is a normal method with a body. An abstract class uses concrete methods for behaviour that is the same for every child, like deposit or printTicket. Then each child writes only the abstract methods, the parts that really differ.
I would write an abstract class Ticket with the shared fields, a constructor that checks them, and a final printTicket() that calls abstract int fare(). Each ticket type extends Ticket, calls super(...) and implements only fare(). A new ticket type is then one small class.
Only constants. Every field in an interface is automatically public static final, so it must get a value where it is declared and can never change. An interface has no normal fields, so it holds no state of its own.
Yes, any number. List them after implements, separated by commas: class SmartPhone implements Camera, MusicPlayer. The class must then implement every method of every interface in the list.
Yes, and the order is fixed: extends first, then implements, as in class Duck extends Bird implements Swimmer, Flyer. Writing implements first gives '{' expected.
void start(); and another has int start();? Can a class implement both?No. A class can have only one start() with no parameters, and Java methods cannot differ only by return type. Whichever return type I pick, javac rejects the other one, for example return type void is not compatible with int. The two contracts simply conflict, so I would rename one of the methods.
Then the class version wins and the interface defaults are ignored, so there is no clash. If SmartPhone extends Device implements Phone, and Device has a public start(), calling start() runs the Device version. That method must be public, though; a package-private start() in Device gives attempting to assign weaker access privileges.
An abstract class can have normal fields, constructors and methods with any access, and a class can extend only one. An interface has only constants, no constructor, public methods (plus private helpers since Java 9), and a class can implement many. Both cannot be instantiated and both can force methods on their implementers.
Lesson: Abstract class or interface? How to chooseDefault methods cannot use instance fields, because an interface holds no state and has no constructor. When classes share data like name and salary, plus code that works on it, an abstract class is still the right tool. Interfaces with defaults are mainly for contracts that can grow.
Payment an abstract class from the start?Then every payment type would be forced into one family and could not extend any other class. Keeping Payment as an interface lets very different classes, like CashPayment or a wallet that already extends something, take part. Shared code can still live in an abstract base class for the types that need it.
An anonymous class is a class with no name that is defined and used to create one object in a single new Interface() { ... } expression. It can implement an interface with several methods and can have its own fields. A lambda is much shorter but works only for functional interfaces.
First I ask what the caller needs, and put that in an interface, because it keeps implementers free to extend anything. Then I look for shared fields or code among the implementers; if there is some, I add an abstract class that implements the interface. If a class needs several such types, they must be interfaces, since a class extends only one class.
Lesson: Common mistakes and practiceI would define an interface Notifier with channel(), maxLength() and a default send(to, msg) that checks the length and prints. A static Notifier.isValid(msg) handles common checks. Each channel implements Notifier, and WhatsApp can override send and reuse Notifier.super.send. The caller loops over a Notifier[], so a new channel is just a new class.
int constants?With int constants the variable is just an int, so any number compiles, two codes can be swapped, and printing shows a number. An enum gives type safety: only valid constants compile, two different enums cannot be mixed up, and printing shows the name.
No. The constants are fixed when the code is compiled; to add one you change the enum and rebuild the app. That is exactly why enums suit days or ticket classes, and not data that users add, like cities or products.
Lesson: Why enums?values() in the java.lang.Enum documentation. Where does it come from?The compiler adds values() and the one-argument valueOf(String) to every enum, because only it knows that enum's constants. Methods like name() and ordinal() are inherited from java.lang.Enum, the class every enum extends.
ordinal() ever useful, then?Yes, while the program runs. It makes a neat array index, for example counts[rating.ordinal()]++ to count votes per rating. The danger is only in storing it somewhere that outlives the current version of the enum.
default in a switch expression over an enum?Not when every constant has a case: the compiler checks that the switch is exhaustive. I usually leave default out on purpose, so that adding a constant gives a compile error at every switch that must handle it.
If the code uses exhaustive switch expressions without default, the compiler lists every one of them as an error. Switches with default and if-else chains are not flagged, so those have to be searched by hand, which is why I avoid them for enums.
fromCode() method when every enum already has valueOf()?valueOf() matches only the Java constant name, like AC_3_TIER. Real data often uses other codes, like 3A on a ticket or SBIN in an IFSC. A static fromCode() loops over values() and matches the constant's own field.
I would write enum Denomination with constants like TEN(10) and FIVE_HUNDRED(500), a private final int value and a getter. Ordered from largest to smallest, a loop over values() can split any amount into notes and coins.
No class can extend an enum. An enum without constant bodies is implicitly final. With constant bodies it is not marked final, because those bodies are its subclasses, but no other class is allowed to extend it.
static final constants or a normal class?I use an enum when the set of values is fixed and known in the code, like order statuses or ticket classes, because the compiler then checks every value. A single fixed number stays a static final constant. Data that users create while the app runs, like students or products, needs a normal class.
I would write enum VehicleType with an abstract charge(int hours) and a body per constant, plus a code field and a fromCode() lookup for the entry gate. A new vehicle type cannot compile without its own charging rule, and the ticket class just calls type.charge(hours).
extends or a field?I use the sentence test: "A X is a Y" versus "A X has a Y". If "is a" is true, I also check that the child can do everything the parent does without breaking its rules. If either check fails, I use a field.
Lesson: HAS-A vs IS-AThe cost is one more object and one more method call, which is tiny for almost every program. A design that keeps the class's rules safe is worth far more than that, so I choose by the sentence test, not by speed.
Lesson: HAS-A vs IS-AAddress class instead of putting city and pin inside Student?The fields belong together and are needed in other places too: a teacher, a shop or a delivery all have addresses. One Address class means the code and checks, like a valid PIN, are written once and reused.
Student s = new Student("Aarav", new Address("Pune", 411001));.The variable s points to a Student object. Inside it, name points to "Aarav" and address points to a separate Address object. That address object has city pointing to "Pune" and pin holding 411001. So there are two objects of my classes, linked by the address reference.
I use an array with a fixed size plus an int count, like Student[] students = new Student[30]; int count;. To add, I check count < students.length, store at students[count] and increase count. Every loop runs to count, because the rest of the array is null.
private Teacher mentor;. Then main sets t = null;, where t was the teacher it passed to setMentor. Does the student lose its mentor?No. t = null; only clears the variable t in main. The student's mentor field holds its own reference to the same teacher object, so the object stays alive and askDoubt still works. That is what "each object lives its own life" means in association.
Yes, in aggregation that is normal: one song in two playlists, one visiting teacher in two departments. Both wholes hold the same object, so a change through one is visible in the other. If the wholes need independent data, they should not share the object.
Lesson: Aggregation: a whole that shares its partsComposition is a strong HAS-A relationship in which the whole creates and owns its parts, and they live only as long as it does. A House creates its Room objects in its constructor and keeps them private; nobody else holds the rooms.
IdCard getCard() { return card; }. What can go wrong?The caller gets a reference to the real card and can change it, for example extend its validity, without the employee knowing. The employee's rules are bypassed. I would return a copy, or better, expose only what is needed, like getCardNumber() and a renew() method that checks rules.
Delegation is a design in which an object receives a request and hands the actual work to another object it holds, called the delegate. For example, Laptop.print(doc) just calls printer.print(doc). The caller talks to one object; the work happens in another.
null, and how do you prevent it?The first forwarded call throws a NullPointerException. I take the delegate as a constructor parameter, check it, and throw an IllegalArgumentException if it is null. If there is a setter, it checks too, or I give a safe default like a "no discount" rule.
Each lesson has quizzes, practice and more interview questions on the same topic.
Open the first lesson