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
A class is a blueprint: it describes what data and actions one kind of thing will have. An object is one real thing made from that class, with its own values, and is also called an instance. For example, Student is a class, while Aarav and Priya are two Student objects.
Lesson: What is object-oriented programming?Not 100%. Java is built around classes and objects, but its primitive types such as int, double and boolean are plain values, not objects. That is why Java is usually called object-oriented, but not purely object-oriented.
Lesson: What is object-oriented programming?No. For a small one-off task, like a temperature converter or a short calculation, plain steps in main are simpler. OOP pays off when there are many things with their own data, like students, accounts or orders, and the program will grow over time.
No. A class only describes objects, the way a house plan is not a house. Objects are created from the class later, while the program runs, and one class can give any number of them.
Lesson: Classes: the blueprint of objectsA public class must be in a file with its exact name, so public class Shop must be in Shop.java. A file has only one name, so it can hold only one public class. A file with no public class is allowed and may have any name; the .class files are still named after the classes.
The object is the actual data on the heap, with its own fields. The reference variable, like s, only holds where that object is, like an arrow pointing to it. s.name means: follow the arrow and use that object's name.
new and give them the same name and marks. Is that one object or two?Two. Every new builds a separate object on the heap, even when the field values are equal: each object has its own identity. So s1 == s2 is false, because == compares the references, not the contents; comparing contents is covered in the Object Class module.
int updated = marks + 5; but the marks do not change. Why?updated is a local variable. It lives only while the method runs, and the field marks was never written. The fix is to assign to the field: marks = marks + 5;.
I would make a Battery class with a level field and two methods, charge(int p) and use(int p). Each method changes the level and then clamps it: above 100 becomes 100, below 0 becomes 0. All changes go through these methods, so the level always stays between 0 and 100.
It is the runtime error you get when you use the dot on a reference that is null, so there is no object to reach. Avoid it by creating objects before use, especially in object arrays. Where null is a normal case, like a free seat, check != null first.
non-static variable cannot be referenced from a static context mean, and how do you fix it?A static method like main has no object, but the field belongs to an object. Java cannot tell whose field you mean. The fix is to create an object in main and use the dot, like app.total, rather than making everything static.
A class is like an admission form template: it lists the boxes every student must fill, like name and marks. Each filled form is an object; there is one template but many forms, each with its own answers.
Lesson: Common mistakes and practiceA constructor has the class name and no return type, and it runs once per object, at new. A method can have any name, must have a return type (even if it is void), and runs every time you call it on an object.
Yes. Java has already made the object and given every field its default value, so printing a field at the top of the constructor shows 0 or null. The constructor only fills in the fields; new hands back the reference after the body finishes.
Student(String name) to a class, and now new Student() elsewhere fails. Why, and how do you fix it?Adding a constructor stopped Java from adding the default one, so the no-argument way of creating a Student is gone. Either update the callers to pass a name, or add a no-argument constructor that sets a sensible value, such as Student() { name = "Not set"; }.
The constructor's. The field initializer runs first, at new, and then the constructor body runs and can change it. So with int start = 5; and start = start * 2; in the constructor, the object ends with 10.
main?Every object has to pass through the constructor, so one check there protects every place that creates the object. If you check in main, any other code that forgets the check can create a bad object. Validating early means an object is never in an impossible state, like a student with 150 marks.
this keyword in Java?this is a reference to the current object: the object being created in a constructor, or the object a method was called on. It lets code inside the class talk about "my own" fields and methods.
this inside main? Why not?No. main is static, so it does not run on any object and there is no current object. javac says non-static variable this cannot be referenced from a static context; you must create an object and use its reference.
this = other; to make the current object become another one?No. this always refers to the current object and cannot be reassigned; javac says cannot assign to 'this'. To copy data, you assign the fields one by one, like this.name = other.name;.
Because callers do not always have every value. With overloads, a ticket can be booked with or without a berth, and the class fills in a sensible default. It keeps calls short and avoids passing dummy values like null or 0.
It is when one constructor calls another constructor of the same class using this(...). Usually the short constructors fill in default values and pass everything to one full constructor, which sets the fields and does the checks.
It is a compile error when constructors call each other in a loop, like A() calling this(1) and A(int) calling this(). javac detects it because the chain would never end. Every chain must end at a constructor that does not call this(...).
Student s = new Student("Aarav", 85); runs.Java makes space for a new Student, and every field gets its default value. Field initializers run, then the constructor body (if it chains with this(...), the full constructor's body runs first). Finally new returns the reference and it is stored in s.
Yes, it can be overloaded with different parameter lists. No, it runs only through new or this(...); s.Student() does not compile. No, it has no return type, so return 5; is an error, though a plain return; is allowed.
Data hiding is only the hiding part: making fields private so outside code cannot touch them directly. Encapsulation is the bigger idea: the data and the methods that work on it are wrapped in one class, and the data is reached only through those methods. So data hiding is one part of encapsulation.
Callers depend only on the public methods. So I can change the inside, like renaming a field or storing the value differently, and I update just one class instead of every place that used the field.
Lesson: Why encapsulation?Default access is what you get with no keyword: any class in the same package can use the member. For fields it is risky because it is easy to forget private, and then other classes can write any value directly.
No. I start with the most closed level and open a method only when a caller really needs it. Every public method is a promise to keep it working, and one more way the object can be misused.
Lesson: private fields and public methodsBecause the class keeps control. A setter can check the value, a field can be made read-only by giving only a getter, and I can change how the data is stored inside without changing any caller.
Lesson: Getters and settersnull. What is the first thing you check?I check whether the setter says name = name; instead of this.name = name;. That line copies the parameter into itself, so the field is never set. It is a very common slip because it gives no error.
So the rule lives in one place. If the range changes later, I edit one method. Copies tend to drift apart: someone fixes one and forgets the other.
Lesson: Keep objects valid with checksI would not use two separate setters, because setting one at a time can break the rule in between. I would write one method, like setDates(in, out), that checks both values together and only then saves both.
int[] and a getter that returns it. What is the problem?The getter returns a reference to the same array, so the caller can change elements like getMarks()[0] = 100 and modify my object without any setter or check. private protects the variable, not the array.
Result class so a published result can never be changed?Private fields, set and validated in the constructor, with a defensive copy of the marks array. Only getters, with a copying getter for the array and computed getters for total and percentage. No setters at all.
Lesson: Read-only fields and computed valuesboolean, and when would it throw an exception?I return false when "no" is a normal outcome, like a full show or a declined payment. I throw IllegalArgumentException when the caller passed a wrong value, and IllegalStateException when the action is not allowed in the current state, like cancelling twice.
If the constructor skips the checks, an object can be born with a bad value, so the class's rule is broken from the very start. The usual fix is to have the constructor call the setter, or a shared private check method, so every way into the object goes through the same check. Then the rule lives in one place and cannot drift apart.
IllegalArgumentException and IllegalStateException?IllegalArgumentException means the value passed in is wrong, like a negative amount. IllegalStateException means the value may be fine but the object is in a state where the action is not allowed, like cancelling a ticket that is already cancelled.
Student objects, how many copies of a static field college are there? And if I create none?One in both cases. The static field is created when the class is loaded and lives with the class, not inside the objects. So it exists even before the first object is made.
Lesson: Instance members and static membersStudent.name for an instance field?Yes, an instance method can read and change static fields freely, since they belong to its class. But Student.name for an instance field is a compile error, because the class name does not say which student's name you mean; you need an object like s1.name.
static from that counter?Then every object gets its own counter, which starts at 0 and is increased only once, in its own constructor. So every object reports 1, and no single field holds the total.
Lesson: Static variablesNo. Static variables live in memory only while the program runs, so the counter starts again from its first value. Real apps store the last number in a file or a database and read it back on start.
Lesson: Static variablesmain method static?When the program starts, no object exists yet. A static main lets the JVM call ClassName.main(args) directly, without creating an object or choosing a constructor. Newer Java (25+) also accepts a shorter instance main, but public static void main(String[] args) remains the standard form.
Methods that work on one object's data, like deposit or getBalance, need that object; making them static would force passing the object everywhere and lose encapsulation. I make a method static only when it truly does not belong to one object, like a percentage or GST helper.
The static block first, once. Then for the first object the instance block and then the constructor, and for the second object the instance block and the constructor again. Their position in the file does not change this order.
Lesson: Static blocksfinal mean for a variable in Java?A final variable can be assigned only once. Any later assignment, including x++, is a compile error: "cannot assign a value to final variable x". It works for local variables, parameters and fields.
No. final Student s only stops s from pointing to another object; s.setMarks(90) still changes the object. To stop changes to the object itself, its fields must be private and final with no setters.
I ask whether the value is the same for every object. A college name, a counter or a shared rate belongs to the class, so it is static. A name, marks or balance differs per object, so it stays an instance field.
Lesson: Common mistakes and practiceThe setup is in the constructor, which runs for every object. Shared one-time setup belongs in a static { } block, which runs only once, the first time the class is used.
No, they are three names for the same idea: the class that is extended. Likewise, subclass, derived class and child class all mean the class that uses extends.
Student extends Person, can a Person object call a method written only in Student?No. Inheritance works one way. The child gets the parent's members, but the parent knows nothing about the child, so the compiler says cannot find symbol.
private, default, protected and public?private is only the class itself. Default is the same package. protected is the same package plus child classes in other packages. public is everyone.
protected any safer than default access?No. Inside the same package they behave the same. protected only adds access for child classes in other packages, so it is a little more open than default, not less.
Single, multilevel and hierarchical. A class can never have two parent classes, so multiple inheritance of classes is not allowed. Java handles that need with interfaces, covered in the Abstraction & Interfaces module.
Lesson: Multilevel and hierarchical inheritanceI would make a Member class with name and ID. Student and Staff extend Member, and Professor and LabAssistant extend Staff, because staff share salary details that students do not. Each class adds only its own fields.
class C extends A, B?javac reports '{' expected at the comma. After one class name it expects the class body, so the error does not even mention multiple inheritance.
super() used for?super(...) calls the parent class's constructor from a child constructor. It lets the parent set up its own fields, including private and final ones, with its own checks.
super(...)?The parent may have no setters, especially for final fields, which only its own constructor can set. Setters can also skip checks that live in the parent's constructor. super(...) reuses the parent's constructor exactly as its author planned.
Person → Employee → Manager, how does a name given to new Manager(...) reach Person?Manager's constructor calls super(name, salary), Employee's constructor calls super(name), and Person's constructor stores it. Each class passes on what it does not own and keeps what it does.
super(...)?The hidden super(); finds no no-argument constructor, so compilation fails with constructor Person in class Person cannot be applied to given types. The fix is to call super(...) with the right values.
Each lesson has quizzes, practice and more interview questions on the same topic.
Open the first lesson