CSC419 ยท 2076 ยท 5 marks
Define class. How do you create a class in Java? Differentiate class with interface.
Define class. How do you create a class in Java? Differentiate class with interface. [5]
Quick answer
A class in Java is a blueprint or template from which objects are created. It defines the properties (fields/attributes) and behaviors (methods) that the objects of that class will have. A class encapsulates data and the methods that operate on that data into a single unit.
Class in Java: Definition, Creation, and Difference with Interface
Definition of Class
Syntax:
class ClassName {
// fields (attributes)
// methods (behaviors)
}
Creating a Class in Java
A class is created using the class keyword followed by the class name. It can contain:
- Fields (variables to store data)
- Methods (functions to define behavior)
- Constructors (to initialize objects)
Example:
class Student {
// Fields
int rollNo;
String name;
// Constructor
Student(int r, String n) {
rollNo = r;
name = n;
}
// Method
void display() {
System.out.println("Roll No: " + rollNo + ", Name: " + name);
}
}
// Using the class
public class Main {
public static void main(String[] args) {
Student s = new Student(1, "Ram"); // object creation
s.display();
}
}
Difference Between Class and Interface
| Basis | Class | Interface |
|---|---|---|
| Keyword | Declared using class keyword | Declared using interface keyword |
| Methods | Can have both abstract and concrete (implemented) methods | All methods are abstract by default (empty body) |
| Fields | Can have instance variables of any type | All fields are public, static, and final by default |
| Instantiation | Objects can be created directly from a class | Cannot be instantiated directly |
| Inheritance | Supports single inheritance (extends) | Supports multiple inheritance (a class can implement multiple interfaces) |
| Access Modifiers | Methods can have any access modifier | Methods are public and abstract by default |
| Constructor | Can have constructors | Cannot have constructors |
| Purpose | Used to define object structure and behavior | Used to achieve abstraction and loose coupling |
| Implementation | A class uses extends to inherit another class | A class uses implements to use an interface |
Key Note
An interface is a blueprint of a class used to achieve:
- Abstraction
- Multiple inheritance (not supported directly with classes in Java)
- Loose coupling
A class that implements an interface must implement all the methods declared in that interface.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.