Confused About Java Inner Class Syntax?

0
10
Asked By CodeExplorer92 On

I'm 16 years old and recently came across some Java syntax that confused me. I have the following code:

```java
Main m = new Main();
Main.Pair p = m.new Pair ("Age", 16);
```

In this code, `Main` is the public class and `Pair` is a non-static inner class. I've never seen syntax like this before, especially the second line. Can anyone help clarify what it means? Thanks!

4 Answers

Answered By JavaGuru74 On

To clarify, static inner classes don’t require an instance of the outer class to be created—so you just call it with `Outer.Inner()`. Non-static inner classes, like `Pair`, are linked to an instance of the outer class. That's why you use `m.new Pair()` where `m` is your created instance of `Main`.

Answered By BeginnerCoder95 On

Just a tip: If you're having trouble with Java, it might be useful to try learning Python or Go. They have simpler syntax that could ease you into programming before jumping back to something like Java.

Answered By LearninFast On

Definitely look up the concept of generics if you haven't already! The `` is Java's way of letting you use types more flexibly without having to specify them every time. In your case, since you've defined `p` to be a `Pair`, you can leave the angle brackets empty during instantiation and Java will infer it automatically.

Answered By SyntaxNinja88 On

It sounds like you're diving into generics! The `` in your code is used for declaring a generic type, which allows you to specify types when creating instances. So your `Pair` class can hold two specified types, a `String` and an `Integer`, in this case. nnSince `Pair` is a non-static inner class, it needs an instance of the outer class `Main` to be created. That’s why you use `m.new Pair ("Age", 16);` instead of just `new Pair();` It associates the `Pair` instance with your `m` object of type `Main`.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.