Inner Class Java Tutorial - Creating and Using Inner Classes

Поделиться
HTML-код
  • Опубликовано: 20 июн 2021
  • Complete Java course: codingwithjohn.thinkific.com/...
    Inner Classes can be a confusing topic when you're a Java beginner (or maybe even a bit more advanced...)
    But creating an inner class in Java is way easier than it seems, and whether you're a Java beginner or further along in your Java career, this video will have you creating your own inner class in Java in no time!
    We'll talk about 3 different types of Java Inner Classes, how you can create them, and how you can use them.
    Learn or improve your Java by watching it being coded live!
    Hi, I'm John! I'm a Lead Java Software Engineer and I've been in the programming industry for more than a decade. I love sharing what I've learned over the years in a way that's understandable for all levels of Java learners.
    Let me know what else you'd like to see!
    Links to any stuff in this description are affiliate links, so if you buy a product through those links I may earn a small commission.
    📕 THE best book to learn Java, Effective Java by Joshua Bloch
    amzn.to/36AfdUu
    📕 One of my favorite programming books, Clean Code by Robert Martin
    amzn.to/3GTPVhf
    🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial
    www.audibletrial.com/johnclean...
    🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
    bit.ly/3QPNGko
    📹Phone I use for recording:
    amzn.to/3HepYJu
    🎙️Microphone I use (classy, I know):
    amzn.to/3AYGdbz
    Donate with PayPal (Thank you so much!)
    www.paypal.com/donate/?hosted...
    ☕Complete Java course:
    codingwithjohn.thinkific.com/...
    codingwithjohn.com

Комментарии • 140

  • @CodingWithJohn
    @CodingWithJohn  3 года назад +56

    Watching this again I just realized I made a mistake with the editing in part of the intro, where I had my face in the corner and a blank rest of the screen. Oh well, hope you all can forgive such a grievous mistake >_>

  • @samuvisser
    @samuvisser 2 года назад +120

    Have been programming in java for years but somehow im hooked on all ur videos lol. Think its learning how to explain concepts in an easy way, ur so darn good at that. Also, had no idea you could create classes in a method! I keep learning

  • @dilln2158
    @dilln2158 3 года назад +23

    This mans gonna get me through university

  • @johntravolta2655
    @johntravolta2655 2 года назад +3

    Poland Computer Science student says thank you !!
    The way you teach is absolutely awesome!

  • @dragosudrea6533
    @dragosudrea6533 Год назад +1

    >Has never seen this being used
    >Still makes a video about it
    Big hustler energy!

  • @aprendeguitarraclasica
    @aprendeguitarraclasica 2 года назад +3

    You just made me interstand this concept after days of frustration. Thanks a lot!

  • @user-vc1oz9rv6v
    @user-vc1oz9rv6v 12 дней назад

    Spent the _whole_ day yesterday reading a book by C. Horstmann, trying to understand the syntax of outer/inner class, trying to understand how the _"this"_ keyword figures into this whole thing, and by the end of the day, I was more confused than I was at the start. I watched this video today and just 8 minutes into it, I understood nearly everything.

  • @jamesdrinkard2751
    @jamesdrinkard2751 Год назад +2

    I've written a lot of different inner classes, but I still learned some things from the video. Kudos to you John!

  • @KingSardius
    @KingSardius 8 месяцев назад

    I learn something new with you every time I revisit familiar subjects. You are great!

  • @fredericoamigo
    @fredericoamigo 2 года назад +1

    Dude, you’re amazing at explaining Java. Thank you so much for these vids!

  • @faheemsyed9481
    @faheemsyed9481 2 года назад +1

    John your style of teaching is simply fabulous. you can make learn a person easily. thanks John.

  • @jlwonders
    @jlwonders 11 месяцев назад

    The best tutorial. I'm so glad to stumble upon this video. Concise. discusses the key important points of inner classes and examples. Very easy to understand how you speak. Well done.

  • @qwerrewq7388
    @qwerrewq7388 3 месяца назад

    This Video just saved me in my Exam, thank you for the great Video

  • @shariefyassin6419
    @shariefyassin6419 2 года назад +1

    I like how simple you make things and explain them , very useful video 👍👍

  • @vladimirguevara3813
    @vladimirguevara3813 2 года назад +7

    Hi John! I'm really thankful to you for all of your videos you really explain very well you make Java looks easy :) so I wanna ask you a video explaining design patterns of course when you can do it.

  • @fc6827
    @fc6827 11 месяцев назад

    Appreciate this explanation about static inner classes, for some reason I keep forgetting what makes it static. Great vid!

  • @deepsuryavanshi6256
    @deepsuryavanshi6256 Год назад

    Thank You very much john, ur teaching style is soooooo awesome I got the info which I was searching for . Hatss offff....
    👍👍🙏

  • @jgabrielmiranda
    @jgabrielmiranda 3 месяца назад

    I've had already read the documentation and understood how ir works but decided to see a video about it, because I was fatigue. And have to admit, your content is amazing. You explained this very fast and well. Congrats! Just sub to the channel. It'll help a lot for sure. Tks for the video.

  • @TheIronWorkshop
    @TheIronWorkshop 2 года назад

    Thanks john, you are a life saver!

  • @JonasKeil
    @JonasKeil 2 года назад +1

    This tutorial is great John!!!

  • @sohamh418
    @sohamh418 2 года назад

    Thanks a lot for making this video, helped me a lot.

  • @stephenweber33
    @stephenweber33 2 года назад +1

    I was waiting until I found a case of inner class before I watched this video. Since you do a great job of instantiation. I found it looking at some example code for the ITERATOR DESIGN PATTERN.

  • @vikastiwari1297
    @vikastiwari1297 2 года назад

    You explain things by telling whats the problem or need of the topic that you're going to explain by giving a example case, It helps so much when i know where can be the concept that i am learning be used instead just watching plain theory tutorials which don't tell the cases where it can be used or whats the problem that may arise if we do things other way.

  • @itsblu4735
    @itsblu4735 2 месяца назад

    Thank you soo much, u made this so easy omgggg!!

  • @felixmorin4611
    @felixmorin4611 2 года назад

    I think i just found the way to solove my problem i have with my code after 10 hs of searching, thank you!

  • @Devivl
    @Devivl Год назад

    Great lesson, John! Thanks!

  • @OgedeiKhanOKOK
    @OgedeiKhanOKOK 2 года назад +2

    Best thing I have learned from this channel is to never be lazy when typing names of stuff 🤣

  • @DaxterSnickers
    @DaxterSnickers 2 года назад +1

    So innerclass are just normal classes in different locations, which you can access with Outername.Innername or inside the method when you create an object there. Got it. Thank you, this really blew my mind.

  • @virajgawand7133
    @virajgawand7133 Год назад

    exactly 2 years later I'm watching this, watched last year for the first time actually :)

  • @Theinatoriinator
    @Theinatoriinator 2 года назад +1

    We use theese to program our frc robot, we have a constants class then inside od the constants class there are inner classes for each subsystem. It its really helpful when you want to keep everything divided and prevent yourself from mixing things up.

  • @jvsnyc
    @jvsnyc 3 года назад +5

    This is great, and is also a great pre-req for an Anonymous Inner Class video you haven't made yet. Between lambdas and default methods in interfaces having been added to Java these days, you don't need anonymous inner classes anywhere near as often as you used to, but sometimes you do, and in older code they were used all over the places, not having those new facilities available yet before Java 8, so if you work with older code sometimes....
    While there are a lot of weird little rules to remember about different kinds of inner classes in Java, that can sometimes get a little tricky, this is a fantastic introduction to the topic. Last detail, some people insist on always referring to the static kind as "nested" and the member kind as "inner", to try to keep things clear. I am often going to those sorts of people for help, so I try to stick to that.

  • @bww705
    @bww705 2 года назад

    Amazing thanks, you videos are the best!

  • @HeisenbergHK
    @HeisenbergHK 2 года назад

    That was just GREAT!
    You didn`t waste my time!

  • @DiverseSituation
    @DiverseSituation 2 года назад

    this was so clear! thanks Johnny, from Noga and Elai

  • @_Anna_Nass_
    @_Anna_Nass_ 2 года назад

    Leaving a comment for the RUclips algorithm because you’re super helpful 😁

  • @kaledbrahmi3442
    @kaledbrahmi3442 3 года назад +18

    Could you do a video about packages in Java? Btw, good explanation, I was struggling to understand inner classes but now is all clear. Thank you

  • @Enanram
    @Enanram 2 года назад +2

    I've recently learned how to use an anonymous inner class to instantiate something like a HashMap and put values straight away. It would be good to learn more about anonymous inner classes and their uses.

  • @coding8453
    @coding8453 2 года назад

    Thanks so much ❤️, now I got what was Map.Entry

  • @jesy1732
    @jesy1732 3 года назад +1

    Just wow! New subscriber 💯.

  • @HeyzonDub
    @HeyzonDub 4 месяца назад

    Thank you so much ❤

  • @redcrafterlppa303
    @redcrafterlppa303 2 года назад

    Node in LinkedList and Pair in Map are great examples for local inner classes

  • @PieMongo
    @PieMongo 3 года назад +3

    Hey you did it! Thank you so much!

    • @CodingWithJohn
      @CodingWithJohn  3 года назад +1

      Hope it helps, thanks for watching!

    • @PieMongo
      @PieMongo 3 года назад

      @@CodingWithJohn it sure does, keep up the good work!

  • @Youtuber-2024-lambda
    @Youtuber-2024-lambda 2 года назад +1

    This is always a pleasure to Watch your vidéos courses, thank you very much John for all your java code passion !

  • @MrMiltersen
    @MrMiltersen 2 года назад

    Hi John!
    Love you videos!
    Would you maybe consider making a few videos about Spring? :)
    Kind regards!

  • @andrealencar8060
    @andrealencar8060 Год назад

    Nice tutorial

  • @user-zb1rt3um6r
    @user-zb1rt3um6r 8 месяцев назад +1

    This guy about to save my semeseter

  • @jasper5016
    @jasper5016 2 года назад

    You are born to teach. Can you please cover design patterns specially SOLID if possible?

  • @dilln2158
    @dilln2158 3 года назад +3

    You should do a java data structures series

  • @MzamoHerbza
    @MzamoHerbza Год назад

    short and straight to the point, I alwyz run away from nested classes. I find them clamssy & difficulty, lol, but from the video, am hooked and eager to use them. Not that difficult... lol

  • @Shva927
    @Shva927 10 месяцев назад

    thank u very much !

  • @ssentongohenryatanus4917
    @ssentongohenryatanus4917 10 месяцев назад

    Hello John!!! I am truly grateful the great work your doing.. Please help me with concerning serialization, deserialization and externalisation. Thank you

  • @MTB_Bay_Area
    @MTB_Bay_Area Год назад

    Thank you

  • @Sollace
    @Sollace 2 года назад

    3:37 Oh wow, you learn something new every day XD

  • @FukSN
    @FukSN 2 года назад

    Thanks 👍👍

  • @AndresGorostidi
    @AndresGorostidi Год назад

    ¡Gracias!

  • @srikanthchitturi7283
    @srikanthchitturi7283 2 года назад +1

    Thanks, I am a big fan of you!! Can you give some real time examples for better understanding..

  • @IndellableHatesHandles
    @IndellableHatesHandles Год назад

    Nested classes are very useful to avoid namespace pollution. Being able to define a static class called "Loader" is a lot less confusing than having a separate class for each thing that needs to be loaded. Instead of your IDE trying to suggest a bunch of loaders all the time.

  • @mykolazhabko3228
    @mykolazhabko3228 2 года назад

    Thanks for tutorial! Simple and clear! Do you have a video explaining interfaces?? How can I use them in game development??

    • @CodingWithJohn
      @CodingWithJohn  2 года назад +5

      Thanks for watching! I don't have a specific one yet, though the video on abstract classes touches on interfaces a bit.
      Basically an interface can be thought of as a contract; if you have a class that "implements" an interface, that is a guarantee that the class will have certain methods that the interface specifies you have to implement.
      Hard to give a specific example for game development, since it's very broad and depends on what you're trying to do in your code. But as a general example, maybe you have many different classes in your game that represent things that can make noise. Character, NPC, Enemy, Animal, Item, etc. They might not be related through normal Java inheritance. You can perhaps have some interface like MakesNoise, that specifies that each class that implements the interface has to implement a makeNoise() method. Then each of those classes can implement that interface, then just implement their own version of makeNoise(). Then anywhere in the code you know that anything that implements that interface is guaranteed to have that method available.

    • @mykolazhabko3228
      @mykolazhabko3228 2 года назад

      @@CodingWithJohn Thank you a lot for replying me. I am developing kind of space shooter like "Space Invaders" with JavaFX for the Univercity course. Using one interface as a storage for constants like GAME_WIDTH. Now I want to use interfaces bit wider. Your explanation is clear to me. Thanks one more time.

  • @adams2736
    @adams2736 2 года назад +1

    One thing missing in this video, explaining why would anyone use inner classes.

  • @prannoyroy5312
    @prannoyroy5312 2 года назад +6

    John, can you give a real life example where an inner class would only make sense to be inside a outer class to help us understand the scenarios?

    • @RogerHolden
      @RogerHolden 2 года назад

      They work well for action listeners...

    • @haltsmaul.
      @haltsmaul. 2 года назад

      Builders

  • @wristdisabledwriter2893
    @wristdisabledwriter2893 3 года назад +5

    I want an example of when it’s more useful to do the inner class than a extended class

    • @CodingWithJohn
      @CodingWithJohn  3 года назад +20

      Broadly, I mostly use them when the inner class I'm making should never be used in any other context than that specific outer class, and you don't want anyone using it by mistake.
      There's one circumstance where I use them often at work - it's a bit of an advanced situation for Java beginners so I didn't talk through it in the video, but I can describe it here.
      The applications we build at my job are web services, and we also often make calls out to other web services to gather more information we need. The structure of the response we receive from those other services is designed by that other team, and we don't have any control over it. But we need to take their response body and map it to a Java object so we can work with it, so we need to represent that response type on our application with a class we make.
      Their response body might look something like this:
      {
      errors: [
      {
      clientErrorCode: "12345",
      clientErrorDescription: "You sent something bad"
      }
      ]
      }
      The "errors" inside that errors list should be their own class, and have a clientErrorCode and clientErrorDescription field, probably with getters and setters. But that class only makes sense in the context of this client's response. Sure, it's possible that right now it might fit in with some other class that has a code and description, but I wouldn't want to couple it with any other functionality in my code that doesn't relate to processing a response from this client. So if this client changes the structure of the response I just have to change this class, and no other code is affected. If I didn't make it an inner class, some other developer might find the class I make called "Error" and use it for something else that it shouldn't be used for, since it only makes sense here.

    • @wristdisabledwriter2893
      @wristdisabledwriter2893 3 года назад +5

      @@CodingWithJohn thank you. That makes a lot of sense

    • @francksgenlecroyant
      @francksgenlecroyant 2 года назад

      Thank you, i am learning a lot from you John

    • @alfredomenezes8814
      @alfredomenezes8814 2 года назад +1

      @@CodingWithJohn Perfect example! I was struggling to grasp some real use cases for inner classes, thank you very much

  • @blehblah1
    @blehblah1 2 года назад +1

    CS student here, we recently learned about linked lists and I'm assuming one of the best ways to implement a node class for a linked list is to use inner classes right? since we only use the node class inside the linked list.

  • @larryd9577
    @larryd9577 2 года назад

    Inner classes are great for private data classes when you are pre java14

  • @anuragdeshpande657
    @anuragdeshpande657 2 года назад

    Please do some on streams

  • @BekTesfa
    @BekTesfa 2 года назад

    Can you talk about the builder pattern while you are on this topic? If I recall correctly inner class is used to build an object of a class using the builder pattern. You thoughts?

  • @yuvaraj9740
    @yuvaraj9740 Год назад

    Unfortunately watched it in 1.25 and all i understood is Outerclass, innerclass, so innerclass outerclass interclass. LOL JK. I understood it perfectly bro thank you! 🖤

  • @johndrowned7170
    @johndrowned7170 Год назад +1

    I love you John

  • @punitgupta7175
    @punitgupta7175 2 года назад +1

    Can you please tell me what is the Usecases, I mean when we should use innerclass?

  • @tsalVlog
    @tsalVlog 2 года назад

    Can you import a static inner class? I'm asking because I came into Java from Kotlin, and am still learning some of the 8-11-isms.

  • @MsRebeca4
    @MsRebeca4 22 дня назад

    It doesn't matter that the static definition for a class is that it cannot instantiate objects because we saw that it can. What is the true definition of a static class?

  • @leetaeryeo5269
    @leetaeryeo5269 2 года назад

    I know this is months late, but I am curious. Can you return a method local internal class object from its local method scope? I’m thinking as like a really weird (and honestly not well designed) object factory method?

  • @teaadvice4996
    @teaadvice4996 Год назад

    if john didn't exist i would be so lost

  • @vasifsultanov4308
    @vasifsultanov4308 2 года назад

    Can you help me with name of color theme which you use in video

  • @joshuamodiba853
    @joshuamodiba853 2 года назад +1

    Ahh my daily bread 🍞

  • @TheAnonymmynona
    @TheAnonymmynona 2 года назад

    This Video explains how to use inner classes well, but what problem do they solve ? When should I use them ?

  • @luckypatiala8298
    @luckypatiala8298 Год назад

    can anybody tell me whats the theme he is using for eclipse and how to download it!

  • @smrtfasizmu6161
    @smrtfasizmu6161 2 года назад

    If I am running my program from a Terminal these nested classé are the only way my code works. If I put classes in different files compiler can't find them, even though If I run that exact same code in an IDE it works. Yes, I am a beginner.

  • @abulka
    @abulka Год назад

    Wouldn't the best use case for inner classes be to make them private and instantiated only by the class within which they reside? Kind of like a local utility class for the class.

  • @AndresGorostidi
    @AndresGorostidi Год назад

    Thks for your videos, John, they are very useful. One thing I did not understand about inner classes.. Can you please clarify if when we are using System.out.println we are using a inner class and how is this defined ? It always confused me the way we did the print out on java, instead calling a simple method of a system class, it seems we are using a kind on inner class. Is that correct?

    • @pixlent
      @pixlent 8 месяцев назад

      (I know I'm a year late, but better late than never)
      System.out simply returns a PrintStream which is another class / object. This method then has the println method. This is very similar to how the builder pattern works

  • @pabloraindogarcia8107
    @pabloraindogarcia8107 2 года назад +1

    Could i ask for a video about composition??

  • @squ1shshr00m
    @squ1shshr00m 10 месяцев назад

    Off topic, but there appears to be something wrong with the subtitles/CC for this video, and I wanted to point it out! There's only an auto-generated Vietnamese option, and when translating the Vietnamese subtitles to English, it's completed unrelated to the video/what's actually being said. No idea what happened there, but I wanted to say something because it doesn't appear anybody else has!!

  • @agent5420
    @agent5420 2 года назад

    Can you please do GUI in java tutorial

  • @mahe7524
    @mahe7524 2 года назад

    The video was great, thank you :-) May God bless you. 1) I know that if you compile the outside class it will be ==> OuterClass.class and OuterClass$InnerClass.class 2) When you want to run it from the command line, do you have to put it in a jar file first? What does this jar file have to look like "inside" so that the entry point is set up correctly? 3) Lastly...how do you run this from the command line and JShell with these scenarios: a)with arguments, without arguments, and b)if using Eclipse...with arguments(Run Configurations set up), without arguments(Run Configurations turned off/cleared out). I've been having trouble with turning "off" Run Configurations lately. After some research I had some trouble understanding this in stackoverflow, sorry. Thanks for reading.

  • @maramhasri163
    @maramhasri163 2 года назад

    Hi Mr.jhon thank you for this video
    but i want to ask you to talk leisurely if you can 🌝

  • @vladimirkraus1438
    @vladimirkraus1438 4 месяца назад

    I think that inner classes are used mostly as private or protected so thay can be instantiated within the code of the outer class. Using the inner classes outside of the code of the outer class is totally weird.

  • @omardumet120
    @omardumet120 3 года назад +1

    niceeee

  • @RajasthaniINAmerica
    @RajasthaniINAmerica 7 месяцев назад

    Sound’s Weird but What is the use of inner class I never used it before ??

  • @DarkOceanShark
    @DarkOceanShark 2 года назад

    Hey, is anyone aware of the Eclipse theme that's being used in this tutorial? Thanks in advance :)

  • @zeppelinmexicano
    @zeppelinmexicano 8 месяцев назад

    Q. What sort of problems are most easily solved using inner classes or method level classes?

  • @chudchadanstud
    @chudchadanstud Год назад

    Is it even good practice to instantiate an inner class outside the outer class? I thought the whole purpose of the Inner class was for it to be used inside the Outer class.

  • @durgaprasadsurada4643
    @durgaprasadsurada4643 2 года назад

    Where and why we use inner class

  • @stefans6557
    @stefans6557 Год назад

    Interesting, but could have a bit more depth, like the proper use of inner data classes in a service class, or whatever.

  • @AndresGorostidi
    @AndresGorostidi Год назад

    John, although it seems you are using eclipse (as I do) for your IDE; I bserved that you did not wrote System.out.println when code, instead it seems you type a shorcut (as sysout) and the IDE expand it to the correct syntaxt System.out.println command. Is that correct ? What pluggin or utility are you using for that ? It would be great if you do a video with those kind of tricks to get the most of your IDE!

    • @CodingWithJohn
      @CodingWithJohn  Год назад

      No plug-in required! It's built into Eclipse. You can just type "sysout" then Ctrl+Enter to autocomplete.
      I also have a full video of Eclipse shortcuts that might be just what you're looking for!
      ruclips.net/video/LIGkIGdmHII/видео.html

  • @duvindudinethmin6820
    @duvindudinethmin6820 2 года назад

    🖤

  • @Gianzero
    @Gianzero 2 года назад

    Good evening, may I ask what code editor do you use? Thanks

    • @CodingWithJohn
      @CodingWithJohn  2 года назад

      Sure! In this video I'm using Eclipse, but in more recent videos (and in my day to day coding) I use IntelliJ.

    • @Gianzero
      @Gianzero 2 года назад

      @@CodingWithJohn Thank you so much!

  • @sureshmanne7245
    @sureshmanne7245 2 года назад

    Did I miss the part of telling why to use Inner classes ?

  • @chanaka7518
    @chanaka7518 Год назад

    😍😍😍😍😍😍😍

  • @feynthefallen
    @feynthefallen 4 месяца назад

    Never used a non static inner class in all my more than 20 years of java...

  • @study-me1oe
    @study-me1oe Год назад

    I have a doubt which most of them don't recognise whether such thing is present or not.
    I know about all the types of Inner classes, came here just for that one doubt which is...
    While creating the NON-STATIC Inner object using the Outer object as below
    Outer.Inner inner=outer.new Inner();
    As we know that the Inner class is non-static, and in order to access the Inner class's constructor, we are using the Outer class object, but how come we are using the Outer class name for accessing Inner class name( Outer.Inner inner ) as in above which should not be possible!!(as the class is non-static, which must be accessed only through the Outer class object) so we have to use the object of the Outer class to access the Inner class object like
    ( outer.Inner inner= outer.new Inner(); ) which should be the correct answer but is wrong!!?
    Please anyone answer this.

    • @study-me1oe
      @study-me1oe Год назад

      above question in simple terms....
      We are accessing outer non static data member( InnerClass ) inside static method( main method)directly . How is it possible?
      ***Outer.Inner inner*** = outer.new Inner();

  • @prameenasenthil526
    @prameenasenthil526 2 года назад

    need jsp servlet videos