<commit_before>---
type: doc
layout: reference
category: "Syntax"
title: "Nested and Inner Classes"
---

# Nested and Inner Classes

Classes can be nested in other classes:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
class Outer {
    private val bar: Int = 1
    class Nested {
        fun foo() = 2
    }
}

val demo = Outer.Nested().foo() // == 2
```

</div>

## Inner classes

A nested class marked as *inner*{: .keyword } can access the members of its outer class. Inner classes carry a reference to an object of an outer class:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
class Outer {
    private val bar: Int = 1<commit_msg>Document that nested classes work with interfaces, too (#1885)<commit_after>---
type: doc
layout: reference
category: "Syntax"
title: "Nested and Inner Classes"
---

# Nested and Inner Classes

Classes can be nested in other classes:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
class Outer {
    private val bar: Int = 1
    class Nested {
        fun foo() = 2
    }
}

val demo = Outer.Nested().foo() // == 2
```

</div>

You can also use interfaces with nesting. All combinations of classes and interfaces are possible: You can nest interfaces in classes, classes in interfaces, and interfaces in interfaces.

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
interface OuterInterface {
    class InnerClass
    interface InnerInterface
}

class OuterClass {
    class InnerClass
    interface InnerInterface
}
```

</div>

## Inner classes

A nested class marked as *inner*{: .keyword } can access the members of its outer class. Inner classes carry a reference to an object of an outer class:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
class Outer {
    private val bar: Int = 1
{'fraction_non_alphanumeric': 0.11411889596602973, 'fraction_numerical': 0.009023354564755838, 'mean_word_length': 3.7721518987341773, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4611319', 'n_tokens_mistral': 611, 'n_tokens_neox': 556, 'n_words': 230}