2076 4

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]

Advanced Java ProgrammingChapter 1: Programming in JavaClass and Object

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

BasisClassInterface
KeywordDeclared using class keywordDeclared using interface keyword
MethodsCan have both abstract and concrete (implemented) methodsAll methods are abstract by default (empty body)
FieldsCan have instance variables of any typeAll fields are public, static, and final by default
InstantiationObjects can be created directly from a classCannot be instantiated directly
InheritanceSupports single inheritance (extends)Supports multiple inheritance (a class can implement multiple interfaces)
Access ModifiersMethods can have any access modifierMethods are public and abstract by default
ConstructorCan have constructorsCannot have constructors
PurposeUsed to define object structure and behaviorUsed to achieve abstraction and loose coupling
ImplementationA class uses extends to inherit another classA 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.