Interface, Abstract class and Inner Class

Inner classes are classes declared inside another class or interface to group related code.


An inner class is a class declared inside another class or interface. Inner classes group related classes and interfaces in one place, making code readable and maintainable. An inner class can access all members of the outer class, including private data members and methods. A non-static inner object is created via an outer object, as in Outer.Inner in = obj.new Inner(); a static nested class can access only static members of the outer class.

Example
TestMemberOuter1.Inner in = obj.new Inner();
in.msg();
Code Snippets 7
Abstract class - cannot be instantiated
Basic

Abstract class - cannot be instantiated

// ------------------------------------------------------------------
// 1. Abstract class - cannot be instantiated
// ------------------------------------------------------------------
abstract class Shape {
  protected String color;
  Shape(String color) {
    this.color = color;
  }
  abstract double area();
  // abstract method (no body)
  void describe() {
    // non-abstract method (has body)
    System.out.println("Shape color : " + color);
  }
}
class Rectangle extends Shape {
  private double length, width;
  Rectangle(String color, double length, double width) {
    super(color);
    this.length = length;
    this.width = width;
  }
  @Override double area() {
    // must implement abstract method
    return length * width;
  }
}
class AbstractExample {
  public static void main(String[] args) {
    // Shape s = new Shape("red");      // ERROR: abstract cannot be instantiated
    Rectangle r = new Rectangle("blue",5, 3);
    r.describe();
    // inherited non-abstract method
    System.out.println("Area = " + r.area());
  }
}

Abstract class example with students (from PPT)
Basic

Abstract class example with students (from PPT)

package vs.abstractExample;
// ------------------------------------------------------------------
// 2. Abstract class example with students (from PPT)
// ------------------------------------------------------------------
abstract class StudentBase {
  protected String name;
  protected int age;
  protected int total;
  public StudentBase(String name, int age) {
    this.name = name;
    this.age = age;
    this.total = 0;
  }
  public void total_marks(int m1, int m2) {
    total = m1 + m2;
    System.out.println("Total = " + total);
  }
  abstract void grade_calc();
  // abstract method
  public void disp_data() {
    System.out.println(name + " " + age);
  }
}
class UGStudent extends StudentBase {
  protected String department;
  public UGStudent(String name, int age, String department) {
    super(name, age);
    this.department = department;
  }
  @Override public void grade_calc() {
    // implementation of abstract method
    String grade;
    int avg = total / 2;
    if(avg >= 90) grade = "O";
    else if(avg >= 80) grade = "S";
    else if(avg >= 70) grade = "A";
    else if(avg >= 60) grade = "B";
    else if(avg >= 50) grade = "C";
    else grade = "F";
    System.out.println("Grade = " + grade);
  }
  @Override public void disp_data() {
    super.disp_data();
    System.out.println("Department = " + department);
  }
}
class AbstractStudentExample {
  public static void main(String[] args) {
    UGStudent s = new UGStudent("Reynold", 20, "Civil");
    s.total_marks(70, 60);
    s.grade_calc();
    s.disp_data();
  }
}

Interface definition & implementation
Basic

Interface definition & implementation

interface MarksProcess {
  void total_marks(int m1, int m2, int m3);
  void grade_calc();
}
class StudMarks implements MarksProcess {
  int total;
  float avg;
  char stud_grade;
  StudMarks() {
    total = 0;
    avg = 0;
    stud_grade = '\0';
  }
  @Override public void total_marks(int m1, int m2, int m3) {
    total = m1 + m2 + m3;
  }
  @Override public void grade_calc() {
    avg = total / 3.0f;
    if(avg >= 90) stud_grade = 'O';
    else if(avg >= 80) stud_grade = 'S';
    else if(avg >= 70) stud_grade = 'A';
    else if(avg >= 60) stud_grade = 'B';
    else if(avg >= 50) stud_grade = 'C';
    else stud_grade = 'F';
  }
  void disp_data() {
    System.out.println("Total Marks = " + total);
    System.out.println("Average     = " + avg);
    System.out.println("Grade       = " + stud_grade);
  }
}
class InterfaceExample {
  public static void main(String[] args) {
    StudMarks s = new StudMarks();
    s.total_marks(80, 70, 60);
    s.grade_calc();
    s.disp_data();
  }
}

Interface hierarchies - child interface extends parent interface
Basic

Interface hierarchies - child interface extends parent interface

interface Payment {
  void pay(int amount);
}
interface Wallet extends Payment {
  // interface extends interface
  void addBalance(int amount);
}
class CreditCard implements Wallet {
  // must implement ALL methods
  private int balance = 0;
  @Override public void addBalance(int amount) {
    balance += amount;
  }
  @Override public void pay(int amount) {
    if(amount <= balance) {
      balance -= amount;
      System.out.println("Paid " + amount + ", remaining " + balance);
    } else {
      System.out.println("Insufficient balance");
    }
  }
}
class InterfaceHierarchyExample {
  public static void main(String[] args) {
    Payment pay = new CreditCard();
    // polymorphism via interface
    ((Wallet) pay).addBalance(500);
    pay.pay(150);
    // calls CreditCard.pay()
  }
}

Multiple inheritance using interfaces
Basic

Multiple inheritance using interfaces

interface Resultable {
  void showResult(int marks);
}
interface Attendable {
  void showAttendance(int days);
}
class StudentWithInterfaces implements Resultable, Attendable {
  @Override public void showResult(int marks) {
    System.out.println("Percentage = " +(marks / 500.0 * 100) + "%");
  }
  @Override public void showAttendance(int days) {
    System.out.println("Attendance = " + days + " days");
  }
}
class MultipleInterfaceExample {
  public static void main(String[] args) {
    StudentWithInterfaces s = new StudentWithInterfaces();
    s.showResult(420);
    s.showAttendance(180);
  }
}

Inner (member/non-static) class
Basic

Inner (member/non-static) class

class TestMemberOuter1 {
  private int data = 30;
  class Inner {
    // inner class
    void msg() {
      System.out.println("data is " + data);
      // can access private data
    }
  }
  public static void main(String[] args) {
    TestMemberOuter1 obj = new TestMemberOuter1();
    TestMemberOuter1.Inner in = obj.new Inner();
    // create inner via outer
    in.msg();
  }
}

Static nested class vs inner class access
Basic

Static nested class vs inner class access

class Outer {
  private static int staticVar = 100;
  private int instanceVar = 200;
  // static nested class - can only access static members of outer
  static class StaticNested {
    void show() {
      System.out.println("staticVar = " + staticVar);
      // System.out.println(instanceVar); // ERROR: not static
    }
  }
  // inner (non-static) class - can access everything
  class InnerClass {
    void show() {
      System.out.println("staticVar   = " + staticVar);
      System.out.println("instanceVar = " + instanceVar);
    }
  }
}
class InnerClassExample {
  public static void main(String[] args) {
    Outer.StaticNested nested = new Outer.StaticNested();
    nested.show();
    Outer outer = new Outer();
    Outer.InnerClass inner = outer.new InnerClass();
    inner.show();
  }
}
Video Lesson Open in new tab
Quiz
1. What is an inner class in Java?
2. Which members of the outer class can an inner class access?
3. How do you create an object of the non-static inner class Inner from an outer object obj?
4. Why are inner classes used?
5. Which statement about nested classes is true?
Coding Problems
1. Write a Java program to demonstrate an inner class that accesses the private data member of its outer class.
Discussion

Login to join the discussion.


No comments yet.