Java Classes and Objects — Java Technical Interview Questions & Answers
Java Classes and Objects
Java Classes and Objects
- A class is a blueprint. An object is a real thing built from that blueprint. The class Student describes what a student has (name, marks) and what a student can do (study). The class alone is not one student sitting in a bench. Only when you write new Student() do you get a real object in memory.
- Let’s take this on the board. class Student { String name; void study() { System.out.println(name + " is studying"); } }. Then Student s = new Student(); s.name = "Asha"; s.study();. Output: Asha is studying. s is not the object. s is a remote — a reference — that points to the object on the heap. The heap is where objects live.
- You can make two objects from one class: Student a = new Student(); Student b = new Student(); a.name = "Asha"; b.name = "Ravi";. Same blueprint, two people. Changing Asha’s name does not change Ravi. That is why we bother with objects instead of one global name variable.
- null means the remote currently points to nothing. Student s = null; then s.study() crashes with NullPointerException. You pointed the remote at empty air and pressed a button. Always create with new (or get a real object) before you call a method.
- Interview line, say it slowly: class = design, object = instance in memory via new. Don’t say “class and object are the same”. The class name Student does not store Asha’s marks. Only the object does.
Class Student (blueprint)
│ new
▼
s1 Asha s2 RaviTechnical Interview Tip: Say blueprint vs instance, then show Student s = new Student();
Code Examples for Java Classes and Objects
Example
class Student {
String name;
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.name = "Asha";
System.out.println(s.name);
}
}Java Classes and Objects — output: Asha. new Student() makes a real object; s.name is a field on that object.
How to Explain Java Classes and Objects to an Interviewer
What is a class?
Blueprint Fields + methods
What is an object?
Real instance Created with new
What is null?
Reference points to no object
Where does the object live?
Heap Reference variable points to it