classes and Objects - Notes by Shariq SP
Classes and Objects in Java
In Java, a class serves as a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of that class will have. Let's explore how to write a class and create objects, along with important details and interview-based questions.
Class Example
To create a class in Java, you use the class
keyword followed by the class name. Here's an example of a simple class:
public class Car {
// Attributes
String brand;
String model;
int year;
// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
// Method
public void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
Object Example
To create an object of a class, you use the new
keyword followed by the class name and constructor (if any). Here's how you create an object of the Car
class:
Car myCar = new Car("Toyota", "Corolla", 2022);
The myCar
object now has its own set of attributes (brand, model, year) and can invoke methods defined in the Car
class.
Important Details about Classes and Objects
- Class: Blueprint for creating objects, defines attributes and methods.
- Object: Instance of a class, encapsulates data and behavior.
- Constructor: Special method used for initializing objects, invoked when an object is created.
- Attributes: Variables declared within a class to represent data/state.
- Methods: Functions defined within a class to perform operations on data.
- Encapsulation: Binding data and methods that operate on that data within a single unit (class).
- Inheritance: Mechanism where a class inherits properties and behaviors from another class.
- Polymorphism: Ability of objects to take on different forms or behaviors based on the context.
- Interview Questions:
- What is a class in Java?
- How do you define attributes and methods in a class?
- Explain the concept of constructor in Java.
- What is the difference between a class and an object?
- How do you create an object of a class in Java?
- What is encapsulation and why is it important?
- Can you inherit a constructor from a superclass?
Multiple Choice Questions (MCQs)
- Which keyword is used to define a class in Java?
class
object
new
instance
- What is the purpose of a constructor in Java?
- To initialize objects
- To declare attributes
- To define methods
- To create classes
- How do you create an object of a class in Java?
create
keywordmake
keywordnew
keywordinstanceOf
keyword
- What is encapsulation in Java?
- Binding data and methods within a class
- Creating multiple instances of a class
- Accessing attributes directly
- Defining subclasses
- Which OOP concept allows a class to inherit properties and behaviors from another class?
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction