.
Inner classes and sub-classes are two different concepts in object-oriented programming, typically found in languages like Java, C++, and Python. They serve distinct purposes and have different characteristics:
1. Inner Class:
- Inner classes are classes defined within another class.
- They are often used for encapsulation and to logically group related classes together.
- Inner classes have access to the members (fields and methods) of the outer class, including private members.
- They are primarily used for improving code organization and readability.
- Inner classes do not inherit from the outer class, and they are not a form of inheritance.
- Inner classes can be instantiated within the context of an instance of the outer class, and they can access instance-specific data of the outer class.
- Example (Java):
```java
public class OuterClass {
private int outerField;
public class InnerClass {
public void doSomething() {
// Inner class can access outerField
outerField = 10;
}
}
}
```
2. Sub-Class (Inheritance):
- A sub-class, also known as a derived class or child class, is a class that inherits attributes and behaviors from another class called the super-class or base class.
- Sub-classes are created to extend or specialize the functionality of the super-class.
- Inheritance is an "is-a" relationship, meaning a sub-class is a type of the super-class.
- Sub-classes inherit the fields and methods (including constructors) of the super-class, and they can add new members or override existing ones.
- Sub-classes can be used to create a hierarchy of classes, with each level of the hierarchy adding or modifying behavior as needed.
- Example (Java):
```java
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
```
In summary, inner classes are used for encapsulation and code organization within a single class, while sub-classes are used for inheritance and building class hierarchies. They serve different purposes and have different relationships with their enclosing or super-classes.