Professional Java - Part 1 | Kenneth DeLong | Skillshare

Playback Speed


1.0x


  • 0.5x
  • 0.75x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 1.75x
  • 2x

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

    • 1.

      00 Welcome

      5:40

    • 2.

      01 Overview

      3:39

    • 3.

      02 Intro to Java

      12:31

    • 4.

      03 JavaIDEs

      3:26

    • 5.

      04 JavaHelloWorld

      10:27

    • 6.

      05 BasicSyntax

      21:54

    • 7.

      06a Objects Classes

      12:39

    • 8.

      06b Objects Attributes

      19:48

    • 9.

      06c Objects Constructors

      18:15

    • 10.

      06d Objects Methods

      29:47

    • 11.

      07 Arrays

      26:55

    • 12.

      08 Collections

      30:20

    • 13.

      09 PolymorphismAndInterfaces

      37:19

    • 14.

      10 Inheritance

      44:38

    • 15.

      11 Conclusion

      1:39

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

113

Students

--

Projects

About This Class

This is the first part of a three-part Java course designed to give you the knowledge needed to program in Java at a professional level. In this first part, we cover Java basics as well as the object-oriented facilities of Java, including classes, polymorphism, and inheritance, as well as basic collections. The class includes a project that you will code from scratch, using the concepts in each chapter to extend the project until we have a working application that applies several sophisticated object-oriented concepts. Students should be prepared to work hard, and should have some previous familiarity with programming concepts such as variable and functions.

Meet Your Teacher

Teacher Profile Image

Kenneth DeLong

Java and Groovy Programmer

Teacher
Level: Intermediate

Class Ratings

Expectations Met?
    Exceeded!
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. 00 Welcome: Okay, everyone, welcome to the professional job. Of course, my name is Kendall Long. I'll be your instructor and guide through this course. Thanks for choosing this course. Let's jump in and see what you're getting yourselves into. So in this course, the objective really is to take you from someone who has very little familiarity with Java to someone who's got a pretty broad understanding of the old key pieces of what a modern job a platform looks like. And really, Mike, my real objective is to give you the tools you need to function in a professional programming environment. Not really. Just to do like your first hello World program or Teoh do a little trick here. They're in Java, but really to give you like the whole suite of knowledge that you need to know to, to be working in a professional environment. So who am I again? My name's Kendall Long. I've been writing software since about the 19 eighties, and in the early nineties I kind of switched from sort of my C and FORTRAN background to starting to use object oriented languages. And in 1997 I switched over to using Java and That's pretty much all I've been programming in since then. I have programmed dunce, a fair amount of python programming and a couple of their fringe languages. Um, I did about 2008 stumble upon the groovy language, which is sort of a supercharged version of Java. Um, I actually have a different class I built about Griffey, but nowadays, in my day job, I used Java and groovy to build back end services for medium sized websites and applications. And currently I'm working with the Internet of things type of architectures. Um, so I'm still very deeply into using Java for my day to day job. And in the early two thousands, I designed and taught a Java two enterprise edition, which that doesn't exist anymore. But that was sort of job is answer to server side programming and online applications back in the day, that was a very interesting and challenging experience. Okay, let's talk about this course. So the course is divided into three parts in the first part. The first half of the first part is sort of, ah, just a basic introduction to Java like this. Syntax the architecture, questions like you know what's a Java virtual machine. How does that work on introduction to the development environments that people use in in professional environments? And then the second half of the class, we're going to get into object orientation. So Java is, at its core an object oriented language. And so if you don't really have a deep understanding of these concepts like objects, classes, polymorphism interfaces, inheritance, things like that, uh, it's difficult to work with, right? So that's the first thing we're gonna talk about in part one. Then in Part two will move on to more of the mechanics of Java, so that's kind of divided into two general areas. There's language features, things that are core parts of the language but are really about object orientation. So they didn't come up in part one. But you know something. Some examples written their packages exception, statics things like that that are definitely key to understand. But it's not really object oriented, um, knowledge. And then in the second half of Part two would talk about the core libraries so Java ships with tens of thousands of classes that implement all kinds of routine programming tasks for you collections dating time libraries input, output, threading. We'll go through and try toe touch on some of the more important ones and give you an overview of of some of the less important one. So you are aware that those things exist. And then in Part three, we go on to some of the things that have been introduced in the last maybe five years of Java, Um, which I've called her modern jobs. So things like generics, although although generics are a little bit older than that, but Lambda function streams annotations, the module system, the functional style of programming. All of this is it somewhat new to Java and, uh, but really, today's powerful java that you see utilized all these things very heavily. So it's very important to understand all those concepts, and that will be what part three is about so prerequisites for this class. So, first of all, I think you should probably have some programming experience before you start this. We're not going to start with this idea of like, what's a variable? What's a function? What does it mean to run a program like if you can't rate, Let's say, 500 lines of code in some other programming language or even in Java. Then you probably need to go do a little bit of studying before you start taking this course, because we don't start from that basic a level. If you do have some job experience, I think that's OK. If you've got some, um, you know, incomplete job experience Number one. It's always nice to have a review of things you've seen before. But number two, you know, if all the topics on that previous slide or not familiar you know, you're definitely gonna learn some new things here. Second is that this is not a frivolous is not like a 45 minute class, right? So there's a ton of information. Job is a huge, huge ecosystem. It's but 25 years old. I think now, at the time of this writing, maybe longer. So there's a ton of things to learn. Even so, we're not going to cover everything, and there will be parts, especially import three word. It starts to get pretty difficult. So, uh, really we're looking for people who are serious about learning how to become fluent at Java . All right, if that all sounds good to you than it sounds good to me. So let's get started on the first section of part one 2. 01 Overview: Okay, welcome to Chapter one of Part one of the professional job class dealing with objects and object orientation. So just to remind you where you are in the sequence is part one of the three part course in this part. We're going to take the first part of the of the course and talk about basic job architecture and syntax and some development environments that are used in professional environments. And then we'll go on to Jabba's object oriented core. Talk about objects in classes and polymorphism and topics like that. So the object is here. Number one. We want to make sure you get a broad introduction to the Java ecosystem. It's complicated, and people toss words around, and sometimes they don't use the words exactly correctly. So it's nice to really have overview of Hubble. The pieces fit together in Java. Then we'll spend most of the rest of the class learning about jobs object during the basis . So Java was created as an object oriented language that is the core of the language, and you really do have to understand that to make the most out of it, and along the way we'll learn a little bit about object oriented design. Now what that means is like, How do you write good programs in an object oriented language that's called object during a design? And although that's not really our focus, we will talk a little bit about that as we go as to how you go about in your thought process of designing a program when you're using an object during that language. Okay, the actual outline of this part would be in the beginning again. The basic job architecture getting and installed. Introduction to some development environments will build a hello world programs. You can get your first bit of code running. Well, then just do a little bit of syntax reviews. So you understand well what the basic constructs look like in job. If this is your first time through and then we'll jump over to talking about object orientation like water classes. What are objects? Raise and collections? Ah, polymorphism with interfaces and inheritance and that'll be the bulk of the of this part of the project of the course. Okay, One of the interesting things you'll get into here is the class project. So our class project is going to be a board game simulation in particular, Um, the game of Sorry. So if you've ever played sorry before, uh, you have a little bit of a head start on the requirements here. I guess what's interesting about this is number one. We build it from scratch. So we start with an empty project and we write all the code 100% by ourselves. Uh, just like you would in a real life, right? And the project builds upon itself from chapter to chapter. So we start when we start doing objects, we start to build out the object, the classes for this game, and we keep on adding more and more and more functionality. So it's not one of those fill in the blank projects where you're handed 200 lines of code and you have to go on a NCAA meant lined 73. And then that's supposed to be your project. This is actually one where you'll actually be coating for real, right, and of course, solutions air provided after each chapter in the video. I'll do the solution together with you so you can see how I do it now. Kind of talk you through it so you can understand how I think about it. And then, of course, that this source code will be in the project area of your course. So you can always look at that. Okay, so the next chapter we're gonna get into the history of Java and a quick introduction to the overall ecosystem and will get the job of virtual machine installed in your computer so we can start writing some code. I will see you there. 3. 02 Intro to Java: Okay, Welcome back to Chapter two. Interested. Job The basics. So in this chapter will just cover some very high level things before we get into the meat of the class. One is sort of the history of Java and the different releases. Because you hear about that quite a lot. Ah, quick top level overview of how Java works and how it's compiled and things like that, and a quick look at the tools that we use to right and compile and work with Java. So in terms of history. So Sun Microsystems was the company that developed Java back in the early 19 nineties, and at the time the feature set was really amazing was a cross platform, uh, programming language, object oriented, multi threaded garbage collected on and on and on. This was a huge deal. Uh, nowadays, of course, in the 21st century, this is all part for the course. But back then, this was a really ah, real game changer. Now, Sun Microsystems got purchased by Oracle in 2010 and since then Oracle has shepherd the development of Java. There have been a bunch of releases of Java, and some of them are here with the released number, the date and just a handful. The main features. There's three things to see on this slight number One is that we're gonna be using java. 11 such Wiese's us down there at the bottom. So that's the version of Java that this course is dealing with. Number two. Just something to notice historically is that there were two major releases of Java that really were game changers, and that was job of five and job eight. That's why those air bold ID So those two releases really made for various reasons. May Java development quite different. There's there's definitely a before and after each one of those releases. Now the third thing to notice is a little bit more subtle. Here is that in the early days of Java, the release is pretty much came every two years roughly, and that was pretty good. Java kept upgrading and getting new capabilities, but notice toward the end. What happened? Java seven took five years job and nine took four years, and the community started to express a lot of frustration that it seemed like Java was unable to push out new features in a timely manner, and so that led Oracle to change the way that job is released. So Java nine was the last major release in the way that previous Java major releases were major. Now what they do, there are twice yearly releases. So after job a nine six months later came Java, 10 after Java. 10 6 months later came Java 11 and someone in support so forth. Job 11 has long term support. So that means, as security bugs, air found and, uh, other updates are necessary to support new hardware platforms or things like that. Job 11 will continue to get attention for the next three years, Other releases say, like Java 12 1 month after Java 13 comes out, the support for Job 12 is ended, so that has some people a little bit nervous. The smaller, more frequent releases are easier to upgrade, but you kind of have a gun to your head because there's only one month that you have before your Java is no longer supported. It doesn't mean it will stop working, but still, in a professional environment that's a little bit scary. So a lot of companies air jumping into this market need right now and which leaves two leads to the question of what is Java anymore. It used to be the job of that came from Oracle was Java. It's a lot more complicated now. So now there's a open source project called Open J. D. K. That is the official reference build of Java. Whatever open J. D. K does, that's what Java does. Everybody else is wrong. This is developed, led by Oracle, of course, but there's a lot of other big companies involved. Red Hat, IBM Azul and a litany of others who are all contribute to this open source. J T K Project Oracle then takes the open J. D K project and adds a lot more enterprise features that adds a lot of standalone utilities that it adds some modules to the job of distribution that have ah more focused on enterprise features. And also there are many other companies that take the open J D kit release and they supported in their own manner. And this is very much similar to to the way you have distributions of Lennox. So you can get Susie Lennix or Debian Lennox or all boon to clinics, and they're all Lennox, but they're all kind of slightly different and have a little bit a little bit different bundles of features. Um, some of them like the one that we're using, which is the Azul Zulu Jabba the community version. They offer different support timetables. So what Azul is saying is like, Okay, you want to use Java 13. That's great. We're going to support it for another two years once Oracle or once the Open J DK projects stops supporting it. So there's a lot of Ah, confusion at the time that I record this, which is early, 2020. I think the market will shake itself out and some strong contenders will emerge. But at the moment we're in a We're in a period of change here. All right, let's move on to the technical aspects of Java. Um, Java is a compiled language. Which would you take your source files and you run a compiler to turn it into binary files , and then those binary fouls or what actually execute. So in Java, we name our source code. We put it in files called dot Java, and the source code is, of course, tax debased. You type it in at your keyboard, you run a compiler. The name of that compiler program is Java Sea, which stands for Java compiler, and what comes out the other side is a class file, which will have the same name as their source file. But instead of dot Java, it will be dot class and the class files air binary and the structure of the of the class file is specified by the job specifications. Now the class files are not directly execute herbal on any hardware. You can't just take a class file, start running it on your Lennox box, for example. Instead, there's another program in there, which is called the Java Virtual Machine. So the Java virtual machine is in. Execute a ble that runs on your computer on your laptop or your server or whatever it is you're running yourself. We're on runs like any other execute herbal. But what the job of Virtual Machine knows how to do is to execute class files. You'll also hear people talk about class files as byte code so, the JBM knows, had execute class files, and that will actually run your program. So if you look down below There's two steps to running a Java program. You take your source code file hello dot java and you run Java Sea on it. That will output hello dot class and then when you want to run that you say job a hello and that starts a jbm and executes the hello class. Now notice the asymmetry here, like when you say when you run the JBM, you don't need to say hello dot class the dot classes assumed, but when you compile, you have to say dot Java now generally, that's not gonna matter to you, but it's kind of nice to know that. So when people talk about Java, there's there's a zillion acronyms and different ways that they talk about it. That can be confusing. So the J R E stands for the Java runtime engine, which is basically the JBM, the Java virtual machine that provides the ability to run Java programs. Then people will talk about the J. D. K the job, a development kit which is the jerry plus the tools to develop and compiled Java programs. So, for example, Java Sea would be included in the J T. K, but not the J R E. And then there's a job SdK, which seems to be the same as the J. D. K but might also include documentation or something like that. These terms are not very crisply defined. It's important to know, because if you go to a website, then you download Java and it says Donald Jr E. You realize you're not gonna be able to compile any could with that, because it's not gonna have the job a C compiler. But if it says joke, download to J. T. K, then you expect to have pretty much everything that you need to develop Java. So it then becomes a question. So what is job? But there's all these different parts, so people talk about the Java ecosystem, which is the programming language. That's basically the syntax rules of How would you write Java code? Then there are all the job of libraries that ship when you download any job, a distribution. There are tens of thousands of library files that people have written over the years to provide functions like, you know, file and put an output and multi threading and lots of different things like that. Then there's a Java virtual machine, which runs the your code on your platform of choice and then also with Java. There's a bunch of command line tools, not just Java and Java Sea, but they also have a bunch of debugging and reverse compilation tools and packaging tools and all kinds of things that that the job a distribution has accrued over the years. Now, just as I noticed, the JV M is considered by most people the crown jewel of this ecosystem. It's it's very sophisticated. It's sort of, you know, some of the cutting edge of computer science, and it runs more languages than job. This is something that's actually really interesting. There are lots of languages that run on the jbm, not just Java. Um, some of the main ones are groovy. Close your Scala, Scotland. There are dozens and dozens more of those four of the major ones that have a lot of traction. But it's very interesting because these languages provide advanced features or just different ways of approaching programming that Java itself does not. But generally they inter operate really, really well with Java because they're running on the same virtual machine, so that's a little bit beyond the scope of this class. But it's interesting to know. Now all of this stuff seems really complicated and you're probably scratching your head. But don't worry. There are I de ese, which are integrated development environments which allow you to develop and compile and package your code inside of gooey based environments like the one you see on the right hand side. Here is Eclipse and we'll be using an I. D in this class because that's how everybody codes job of these days. And it really will, uh, abstract a lot of these problems for you. Make it easy, and they'll just take care of a lot of the stuff we talked about, so you don't really have to worry that much about it. However, if you're going to start working in Java, you will come across a bunch of those issues. So it's good to know that all those things exist. All right, your exercise for this chapter is going to be to get Job 11 installed in your computer. All right, now again, I'm using the Zulu Zulu community edition of job 11. Um, and you're certainly welcome to use that you can use pretty much any job. 11. I don't think we shouldn't be touching on any features that are not in core. Job 11. I'm not going to give you here or in the product Second project section. Any instructions on how to install Java? Because it does kind of change from time to time and the different depending on which distribution you use. They may have a different kind of installed er, so just follow their instructions. Make sure you get the J. D. K, not the J. R. E. If they offer two different ones and when it's done, you should be able to open the command prompt like you see in the slide hair and you say Java dash version and it should come out and you should see a bunch of Elevens There, Right here we see open J. D. K version 11 dot zeroed up five. So that tells us that this is job 11. Um, October 15th 2019 Long term support version. Okay, so this is the official job. A build job 11 billed as of October 15th of 2019 so you should be able to do that. You should be able open the command line version, say Java dash version and get some kind of output like this. If you're using Zulu, it should pretty much look like this. There may be some updates from the time I've written, you know, done this course, but in any event, that's your homework for this section. And once you get that done, meet you in the next chapter and we'll talk about how to install an I. D. E. And then we'll have all our tooling ready to dive into actual jobless in Texas. Talk to you then. 4. 03 JavaIDEs: Okay. Welcome everybody to Chapter three Java I ds. Let's get set up to start banging out some code. All right, so this chapter is a short one just to learn, install an I D. E and get ourselves in the position toe, Start writing some code. Now, you might be saying an idea. What? Okay. I d e stands for integrated development in But environment, which is a combination editor, Compiler de bugger Runner, Everything you need to develop code And I just point out that these things are crazy, powerful. When you compile a programming language, the compiler creates a data structure called the abstract Syntax Tree which tells the compiler you know what your code means and what it does. These I d Ys are plugged into the A S t abstracts in texture. And so they conduce things in editing and re factoring your code that a text editor just wouldn't be able to know. I mean, they do some very sophisticated stuff. However, if you are like a nemax guru or something like that, and you think you can be way more productive with that than feel free. However, for most of us using an 90 e is going to be the way that we're spend our days as a professional coder. So what are the popular I Ds? Well, as of the time of this course, the main ones Aaron, tell Ajay from a company called Jetbrains, and that seems to be the one that has the biggest mindshare right now. Then there's Eclipse, which I believe is the original I D E for Java. It dates to at least the year 2000 if not before that. And then there's net beans, which I believe was started by Sun Microsystems. Now it's sponsored by Oracle that seems to be less popular than intelligent or eclipse in this class. I'm going to be using clips when we do when we do our project work, and I reviewed the solutions with you. I'll be working in eclipse, but it really doesn't matter. They all do pretty much the same thing. The class and the projects don't depend on your choice of I d. E. We're not going to do a lot of learning how to use the ideas. I'll show you some things in a video basic eclipse commands just to get you started. Um, The important thing is just to pick one, download it again, install it according to their instructions. It's going to be different for each one, and the instructions do change from time to time. But just remember that developing and job as much easier if you have a good idea and you get really good at using using it. So that's definitely a worthwhile investment if you're looking to become a job, a programmer and that's it. So the exercise for this chapter is to install one of the popular I DS and get it going. So again, look up their website for installation instructions. Some of them will offer multiple additions, and some of the additions will be paid other ones. They're going to have all kinds of extra functionality for the purpose of this class. You just need the basic Java developer edition, whatever that's called in in the I D. That you pick. Uh, that should be free. You should be able to install that later on. When you start to do more sophisticated things, you can think about maybe moving up to a paid version, but that that's not necessary for this class. And then once we have that installed and it's working. Then in the next chapter, we're going to start programming. All right, we'll see that. 5. 04 JavaHelloWorld: All right, Welcome to Chapter four, Java, Hello world, where we're going to write our first executing code. So in this class, we're just gonna learn about the format of job of source code files and how to start the execution of a Java program using what's known as the main method. So Java source code is put into files which people tend to call class files because they contain classes That's different than the class files we talked about before, which are the binary files produced by the compiler. So the nomenclature is a little bit, um, confusing sometimes. But let's say you wanted to create a class called my class. You would write a file called my class dot Java, And then inside that file, you would have this incantation here, public class, my class followed by curly braces. So what's going on here? The first of all the class name that you define anger source code must be the same as the name of the file name before the dot job. So if it's public class, my class, it has to be my class, not job. And then the curly braces denote the scope of the class So, um, what scope Means is basically just a group of statements that belong together. If you do some python programming, you'll know that scope is denoted by the level of indentation. If you indented your code underneath, say, like an if statement, that denotes a block of code that goes together in Java. In any language that descends from the C programming language, we use curly braces to denote scope. All right, Java programs begin executing at a method called the main method and main method. Looks like this. This is standard, ah, format. Ford is public static void main string bracket bracket arguments. The bracket bracket means array, and we'll talk about that in a few chapters. Annette's where, when you invoke this class from the command line, this is where the execution will start. The ARDS refer to the any parameters or arguments that you passed in on the command line. So that's how you would pass in command line arguments into the program that they're available ized as the argument org's Now, for the most part in your Java programming life, you don't right a lot of main methods, and even if you do as well see the I d e will create them for you, so you don't really have to worry too much about all this syntax. But it is worth noting this is something that people have banged Java in the past four. So just to get some program running, there's a lot of syntax there. What's a class? What is public? Me. Want a static? Me? What's void all about? What is the square brackets doing? There's a lot of things in there that that require explanation. Uh, we'll go through all of those things as we go through the class. For now, you can just take the main method as sort of, ah given format that you always use. Okay, so we have some code executing, but it didn't do anything. So let's do. The simplest thing that everybody does is print out hello World to the Council. So again, in Java, like getting something to print to the console is a little bit verbose, its system dot out dot print Lynn and then the string that you want to print to standard out. So just for your reference system is a class that's in Java. Out is the output stream as it's called, which is a static variable in the system class and then print line is the method that says Prince Align, print this code and then follow up with the line feet character Turn again. You don't need to really worry about that. It's the same all the time system out. Kremlin just treated as one long thing that you type out. Don't worry too much about the components. Now, if you were going to run our little program that we just wrote at the command line, you do it like this, you'd run Java Sea over my class dot job A to produce my class, that class, which is the real actual class file. And then you'd execute that class file on the jbm by saying job of my class and that would execute the program starting at the main method. And what you would see is hello, world print out to the council. Now we're going to use the I D. So I'm going to switch over to switch over to Eclipse to show you how it works in eclipse, and I'll walk you through this first program just in case you're brand new to it. the other ideas will be very similar. The keyboard shortcuts and the menus. They're going to be slightly different, but it all works pretty much the same. Okay, if this is the first time you've ever installed Eclipse or open it up in your workspace here you'll get this welcome dashboard screen, which has links to a bunch of tutorials and things like that. I don't want to see this, and I don't want to see it again, So I'm going to go directly to what they call the workbench. Okay, so this is the view where you're gonna be working. I'd like to have a little more real estates. I'm gonna close some of these windows that I'm not gonna need, and we're ready to write some code, but you need to know that you can't just generally in these i d. E. S start writing individual files. You have to put them into a project. And a project really is just a folder on your laptop. So let's create a new here. We have a link creating new job a project. Let's do that. We'll call it Hello world. Oops. That's the space out of it. Of the world used J to Java. 11. Create separate folders for sourcing class files. You have this option that the class files might go into the same folder as the source files . If you click this, I think everybody puts them in separate files, separate folders. And then on this page in Eclipse, there's this one thing that I like you to notice. Create the module info dot Java file. Let's not do that, okay, that just causes that. That that's part of something we'll talk about later in the course called the Java nine module system Just causes a lot of extra complication doesn't help us at all right now, So let's just get rid of that and then create the project. Now. When I opened the project that there's a folder here called SRC, that's where your source goes and let's create a hello World Java class. Now. How might one do that? Well, the way you do it in Eclipse, that's just right. Click on the source folder and you say new and it says class. Okay, let's do in the class and I'll call this class. Hello world. It's OK to name the class the same thing as the as the project notice that eclipses saying , Hey, you're putting this in the default package. That's discouraged. We haven't talked about packages yet. We'll do that much later in the class, and then we'll tell you how to fix that warning. Now, notice There's all kinds of stuff here. You can click most of it Doesn't matter. Except right now it says, Would you like me to step about the public static void? Main methods? Yeah, sure. Why don't you write that for me, then? I don't have to do it. And here comes Okay, so, uh, we get this. And personally, I like the curly braces on the other lines. I'm gonna do that. There's this Ah, to do statement put in here for you. So you don't forget to come back and fix this. But what we wanted to do was just what we had in our in our slides system. Got out that print land puts notice how, uh, the editor knows what? Um, functions are available. So again, something that a text editor wouldn't help you with Risk was say hello world with an exclamation point. Remember? Everything ends with semi colon. Save that file. And there you go. There's your first job program. Now. How do you run it in Eclipse? You can go back to this left hand panel the way I generally do it right, click on it and say, Run as a job application. Sometimes there's multiple ways for Eclipse to interpret a given file, depending how complicated your code is. Right now. There's only one way that's has a job application. You run it and the consul comes up and here's where your output goes. Hello, world, right? And if you want to prove that you can change the text a little bit, you can run it again and you can see that it changed. So it really is our source code that's running here. Okay, so that's an introduction to Eclipse. That should be almost enough to get you through the first couple phases of our project. There's really not much more to it than that. Obviously, if you explore the menus and things and eclipse all the pop up menus in the top line menus , there's a ton of things that you can do in here, most of which we don't really need to worry about. For our class. All right, back to the slides. So what the The exercises for this particular chapter is to do just what I did. Get your first hello world program running. So get your your i d open create a little hello world project and just get the, um, get the thing running in printing to the council in the project area. There are instructions for this. It will be labeled 04 Hello world, which is the same as the chapter name. So you can track those together. So if you want a little bit deeper, um, explanations on what to do Take a look at that file. So go ahead and do that now and then in the next. Uh, well, just to summarize what we talked about. Remember, Java programs begin their execution at the main method. The code is contained in the class file in the class file has a main method and, uh, parameters that you passed to the function system that out that print Lynn are then printed to the consul. Okay, we're gonna use those fax quite a bit in the rest of the class. So once you've got that working in your I d. Then we're ready for the next chapter, which will be all about classes and objects. So this is where we're really going to get into it. All right, we'll see then. 6. 05 BasicSyntax: All right, Welcome to Chapter five. Jobless in Texas. In this chapter, we're just going to go over some of the basic Java syntax. I'm not going to be Labour. This ah lot of it is pretty self explanatory, but it is important to at least see it one time before you start working on Java. If you've programmed any job of before, you'll probably become a bored by this. But it's good for everyone Teoh to see all the different syntactical constructs that are coming going to come along, including these things Naming conventions, types, variables, statements, blocks conditional is four leaps all these kinds of basic building blocks of the programming language. Okay, job A does have its own spelling conventions. These were not enforced by the compiler, but everyone does it this way, and people will be unhappy if you write things differently. So in Java we used what's called Camel case, which means that the words are strung together and new words have the first letter capitalize. So it has humps like you see here on this camel case versus other cases. For example, Snake case. This is how Python likes to do where you put underscores between the words and leave them all. Lower case eso Campbell cases The standard way of doing things in Java class names are generally always capitalized. Constants air made all caps the way you see it here in concept constant because they're all caps. They do use the underscore to separate the words, but pretty much everything else starts lower Case and Uses Camel Case If there's multiple words in the name that would be variables and method names and package names and anything else you can imagine, Okay, One thing that's interesting about Java from the point of view of an object oriented language is it has some types in that are not objects. They're what we call primitives, and these are the ones you see here. I won't read this chart. You have it for reference. But these air not objects in the sense that most Java classes are. But these air types that you can use that are just numerical and character and bullying and bite types, okay, declaring variables. So job is one of those languages where you need to declare the variable before you use it. You have to tell the compiler I'm going to use this parable called I and It's an Int, which is a primitive imager, right? You can declare a variable like that and then assigning values to it later on. Or you can do it like you see with the line below with pie, where you declare the variable and initialize it in the same statement. Both of those air fine moving to the bottom. There we see that statements and java are always terminated by semicolons, right? There's a lot of programming languages where the compiler infers the end of the line by the carriage return at the end of the end of line, but nothing job. It's only the semi colon that denotes the end of line and white spaces. Ignored comments. If you put in a double slash into a line of code, the compiler then considers everything from the double slash to the end of the line as a comment. So you condone you can write some code and then put a double slash. After that, you can just start a line with a double slash that makes it turns it into a comment. If you need multi line comments, you do a slash star and then everything from then on is a comment until you do the star slash Okay, strings in any programming language are a real workhorse, and there's some special syntax for strings in Java, which would probably be completely under up. Completely accepted are expected, rather so on the first line. There you see with my class if you're creating an instance of a class, and we haven't really talked about what that means yet, but normally have to use something called the new operator to create an instance of a class for strings. You don't need to do that. You almost never see anyone do new string. What you can do is just put your string in double quotes, and the compiler will automatically create a string object for you because strings are objects as well, and then assign it to the to the message variable. So that's kind of ah, special string, literal syntax. Other cool things you can do with strings on the bottom right is you can contaminate them with the plus sign. So you see this message equals two plus words, and then when we do our system out Kremlin, we can even can Captain eight. A *** with the string, as you see there in the message, plus I, and like the call out shows, it will print two words colon to So all those will be contaminated. The integer I will be turned into its string representation when you try to print it, and so that's all very convenient. Correct condition. ALS. So Java uses the same sin taxes C or C plus plus any C language. Uh, C programming language, family of languages. And if the Boolean expression inside the parentheses evaluates to true, then the block following that, that statement executes. If you haven't else if and an else if and else than in that whole block only one of those blocks will execute. So as we see here, we have ah, J equals five. And then we say, If J is less than four, do that well, no, that's false. If J is greater than six milk, that's false. And so we dropped down to the final else statement, which is the one that would execute Boolean. Operators can use all the little, uh, types of operators you see on the right hand side. There, the less than greater than equal, equal, not equal war and and one other thing about condition. ALS, although generally when you write in if statement, you'll put curly braces after it to group the code that comes after it into a block. If there's only one line, you don't need the curly braces. So if you're just having like like the example, it's on this page with the system that out dot print Linds, you really don't need the curly braces. But it's considered good practice to put them in. If you do have only one line following your if the standard way to do it is how it looks at the bottom right where you put it on the same line as the statement just to emphasize the 10.2 people that hey, this is a single line If statement Okay, this switch statement, uh, this is similar again to lots of other languages where you're switching on some value, J um, you have with the cases within the switch statement, and whatever matches is what will execute, um, looking at the case to case three. So, for example, let's say if J is equal to two matches, case to it will continue to execute down the list of statements until it gets to a break statement. Okay, so generally, on each case, when you're done at the end, you need to put a brake there. That's a typical gotcha for programmers at the bottom. There's also a default section, which, of course, executes if none of the cases above match. Um, generally, you have a default when you write a switch, but not necessarily all the time. Okay, while loops and do loop. So a wild loop is kind of like in its statement, in the sense that it takes a Boolean expression. But the while loop will keep executing its block until that expression turns false right? So it's exactly what it says while Jay's Lesson 10. Do this stuff here, of course, Within that loop, you better be changing the conditional or else it's just gonna be an infinite loop, right? If you said while five is less than 10 and then you put a block of code there, that's going to be an infinite loop, so be careful. You can also reverse the order. You can say do the block first, while there's a condition and that's called to do while loop. Um, for whatever reason, those aren't really that common to see in everyday code, but certainly balance in Texas. Okay, the increment and Decker Ament off operators again if you've done C or C plus plus, you know all this already. But if you haven't other languages may not have this kind of syntax. If you have an integer variable like Jay and you say, J Plus Plus, that's the same as saying, J equals J Plus one or J minus minus. That's a detriment. J equals J minus one. Okay, so these air shortcuts for incremental and deck remaining and then if you dropped to the bottom, there's a post fix and a prefix notation. So what that means is, when you say J plus plus it says, execute this statement, and when you're done increment J. In the bottom line, you see where it says system out. Berlin Plus Plus J And what that tells the compiler is first increment J. And then execute this statement so you can see in the call outs with the results of those of that little bit of coding there would would print out. There's one other shortcuts in text you have over here on the right hand side. Let's say you have an energy. J equals one, and you say J plus equals four. That means J equals J plus four. So instead of an increment, it's adding some extra value that you supply and then assigning that back to the original that variable so you'll see this kind of short cuts in tax all over the place, especially here in the fourth. This is a riel bread and butter of programmers, and the four loop has a four statement that has three sections and then followed by the block of code that gets looped over that gets repeatedly executed. So generally there's some. The typical way you see this is there is a loop counter and in this case that that one is the variable J, and you declare it in the first section. J equals zero case that that creates the variable J and initialize it zero. Then you see a semicolon. Then, on the next second section, there's a Boolean expression which says, keep executing this loop or stop right, and that will be evaluated at the top of each loop as it loops around this as it loops around this for loop. And then on the third expression after the second semi colon, where it says J plus Plus, that's the sort of ah, loop, end of the loop work that you do. And so in this case, this is a very standard for loop. Or you're just saying I want to look this thing 10 times and so you're just creating a counter. You're saying Counter equal zero while the counters less than 10 do this and then counter plus plus. And that's a very standard syntax. Now you don't have to have a loop counter. That's an integer like this in your four loops. There's other ways of doing this. It's just kind of limited to your imagination, but this is the standards in text. Three, um, a new initialization statement. Ah, Boolean expression. And then some kind of work to do at the end of the loop, followed by a block of code tickets executed each time the loop goes through. So this particular uh, four loop that's on the screen would print out 0123456 79 and then it would stop okay within four loops, you conduce. Um and this also works for where wild loops and do loops as well. We have two special keywords. Break and continue. So what break says is I'm sorry to start with continue. What continue says is if you get to a continue statement inside of a for loop, we abort the rest of the block of code that's executing their we do the look maintenance clause, the third clause, the J plus plus. And then we go back to the top and start again. OK, so continue Just says, Okay, stop this loop of the this time through the loop, go back to the top and start again. Pretend that you finished the whole thing. And then the second keyword is break which says, Just stop executing this loop continually. Just pretend you reach the end and skip out and and continue with the rest of the source code. And so here we have a loop that runs from, uh, J equals zero j less than 10. So the values that J takes home will be zero through nine. And when if J is less than five, that continues, so it doesn't get to the system out print line statement so nothing is printed once J gets to five, then we no longer execute that continue statement because it's guarded by a conditional there. And now we start to print out on the bottom. Right. You see the output? 567 eight. But on the time we get to eight now, the third statement in the loop, if j greater than seven now becomes true and we hit the brakes statement and we pop out of the loop and we never get a chance to print out number nine because we when when j equals eight, we hit the brakes. Statement in the loop, terminates, breaking continue are very important to understand. Okay, so that was a pretty whirlwind tour. Uh, we're gonna have an extra exercise now toe help you deal with with this Skype type of Syntex and the instructions air in the instruction sheet called 05 basic syntax. And we'll do go ahead and take your time right now to go and do that exercise. You can pause the video and then when you're done, you can start the video up again, and then I will be doing that exercise live in the video. So in case there was anything that you weren't quite sure about or you wanted to just hear what I have to say about it. Um, that's going to follow as soon as you're done here. All right, let's take a look at the basic syntax exercise that we had in the project area. I'll just go through all the steps of the exercise, just in case you were curious to hear how it worked out are, you know, look at some way of doing it. So, uh, it says just take the hello World Project from the previous chapter. All we're gonna do is fiddle with the syntax in the main method that we wrote before and and see how it works. So number one says declare three. Ended your variables. I j and K a sign Variable values toe I NJ and let k be the some and print the value. Okay, well, that's easy enough. So but, uh, get a little bit of space here and we say, Fine, let's make that equal four. And J equals two tenant king because I j okay. And then it says, print them out. Uh, there's a little bit of a shortcut here. An eclipse that does. I went S Y S O and then controlled space. And that's what they call a template. An eclipse. But let's do this. Then it fills it in for personnel. I got to run this. I can actually click inside the file and say, Run as job application and it prints six, which is what four plus two should be right then, like a be the difference in the product and print those values in turn. So basically, it's what it means. Is this KB the difference? So I minus j right print K. And then the product means multiplication. Well, and there we go 6 to 8. Exactly what you'd expect to see. Okay, um number three now create another variable Acts of type double. Look, the quotient of I NJ Let X be the question of my engine. Print the answer. Okay, so let's do this. We will see what we're getting at here. Double X equals I colder, J um, and let's do something here to make this more interesting. Let's change I 25 These results will be a little bit more interesting. Uh, oops. X By the way, I'm just hitting. If you're using Eclipse on Windows, I'm using Control F 11 and that says, Run the execute herbal again. So the first time I have to right click and save run as Java application. But after that, I'm just control If 11 control after 11. Okay, so what we got is I over J, which is five divided by two, and that's equal to 2.0. That seems a little odd. And in fact, number three A says did. Then it's air coming out a little bit strange. And the answer is, yeah, because dividing images by imagers always returns an imager, even though we assign it to this double precision variable X. So what happens is I divides by J that creates to the energy to and then that gets changed into a double in order to assign it to X. That's not really what we expected. So what we need to do is change either I or J to be not uninjured. And the typical way of doing that, as noted in the in the book, is to multiply by 1.0. All right, it's kind of a not looking thing to do. But this way multiplication of 1.0 times I changes I into a floating point number, double precision number. And then you divide by Jason. Now we have 5.0 divided by two. And what we should get is 2.5. That's what we would expect. All right, let's go. Let's see what else we have. Create a loop that prints count zero count one blah, blah, blah, blah up to count. Name. All right, so this is a for loop problem. Now. I can't really say into I equals zero here. Let's see, the compiler is going to say Wait, you've already used I And he's correct. So and I've used I j in case let's use in as a loop here. Or another thing I could do is instead of declaring a new, valuable very well, I could just say I groups I equals zero cry less than 10 I plus plus. So that's another possible way of doing. Or you could have said int in equal zero and less than 10 and plus. Plus, they both work and we're gonna print count. OK, so count space plus high. Let's run this and see what happens. Let me get a little bit more visibility here on the on the council. All right, so there we go. You see? Count zero to count nine. Now, what's the next thing if the output is going to be count seven. Also, print bingo. All right. Interesting. So what I can say is, if I people seven. Let's try that. There we go. You see? Down here? One is as the count seven. You get bingo notice. I put the statement on the same line as if now you don't have to write member job. Ignores White speaks. Right. So you could do this. You could even do this. That's really confusing to the people who come after you. And the reason people generally don't like this either is because it kind of looks like a normal for loop. And you might see curly braces. There were. You were they don't existing. You might start doing something like this. You know, K equals four and think that it's part of the four loop or the If Bloc. Rather it's not right. So in order to keep people from thinking that generally we do this. Okay. Anyway, What's our next little bit of magic here? Um, don't print anything if the count is less than three. So there's two ways to do this here, right? Um, one would be to say, Well, that sounds conditional, writes I'm going to say if I is greater looks greater than or equal to three. Then do the cash, my taping his nuts again. There we go. So that works. It did say if the output is less than three, don't print it. That's one way of doing that. Another way of doing that is to exercise some of your breaking. Continue. Okay, so you say if I is less than three continued, so not break. Because if you break the four loop will terminate and won't run anymore. And you contest that if you if you want to. But continue says keep going. But just skip the body of the block for these values and exit the loop if the count is eight or larger. Okay, Well, you know what? That No, it didn't say whether we should still print eight or not. Let's go ahead and print it going to be nice. If by is greater than or equal to eat brink. Right. So there we go. It stops at eight. Now, it doesn't print nine. And just to make sure this is understood, um, let's put another statement after the loop. Once you break out of the loop, execution continues right below the. So what we should see is after the count eight. We should see it. Go. Done. Okay, there we go. So that's a little bit of kind of scribbling with java just to practice with some of the, uh, syntax elements that that we have in Java. Uh, we didn't use everything, of course, but hopefully that gets you used to writing some lines of code. All right, In the next chapter, we will start talking about classes and objects. So that's when the fun starts. We'll see that 7. 06a Objects Classes: Okay, Welcome back to Chapter six, where we start to dive into classes and the foundations of object oriented programming. So just visit Overview for this chapter object during the program is based on classes. Job is object oriented. All Java code occurs inside of a class. Therefore, we need to learn what classes are. Okay, this is a really long chapter. So I've broken it up into four sections on classes, attributes constructors and methods and will do them 12 time at the end of each section. They'll be a little bit of work on our project, and by the time we finished, the chapter will have it. The project running in a rudimentary fashion. Okay, so Section A what? The hacker classes anyway. So what's the point? Why all this hoopla about object orientation and classes and things like that? Well, this is a deep discussion, but for starters, you can imagine someone who, from the product team coming and say, Hey, customers can have two accounts, and then the developer responds with some developer gobbledygook. What's the problem here? Well, there's clearly a communication gap between the two. The product owner has zero confidence that the developer understands anything of what they just said. There's very little ability to track what's going on. And the developer maybe would make a mistake. Maybe they got one of these gobbledygook names wrong, right? Would it be nicer if the developer said something like this? Hug one of the customer class and had another account? Oh, okay, now number one, there's less translation going back and forth between the two vocabularies and number two, the developer can actually talk to the product person. All right, this is a toy example here, But when you talk about a large project with dozens and dozens and dozens of names, and if they're all translated from customers, speak to engineer speak. That really does put a burden on your brain of trying to translate all that stuff constantly. It's kind of like the the good product people are talking in English and you're thinking and Russian or something, or vice versa. Another reason that people talk about object orientation is that, um by building that the concepts of the software based on the concepts of the problem. So in other words, if you have ah, your product, people talk about customers and accounts. If you structure your software around the concepts of customers and accounts, that's probably a pretty stable base. For example, if you're building a library, you know, library has resource is to lend. They have librarians. They have patrons. They have loans of. Resource is that's kind of been the situation for centuries. Right? So your software is probably safe organizing around that, um, way of finding the architecture. Okay, So where did these classes come from? Well, generally, they're inspired by the noun in the problem description. All right, So Okay, what now? What are we saying? Let's go ahead and look at our project, and then we'll figure out what some classes in it might be. So what's our project gonna be? We're gonna be building a simulation of a board game loosely based on the board game called . Sorry. If you've ever played that, you'll know what I'm talking about. If not, don't worry. We're gonna do it. Dumbed down version of it. So very loosely. There's a board with 60 squares. Multiple players can play the game. They can each have multiple pieces, the pieces air sitting on one square at any given time and There's a deck of cards that you draw from, and it tells you how to move the peace right at the moment. For this iteration, we're only going to consider cards that move peace forward. But if you're familiar with sorry, you know there's different types of cards that move the piece backwards and do other kind of crazy things. So later on, we'll introduce some of that. Okay, this is actually good enough. This little, you know, 50 word problem description is good enough to start doing in some analysis on if you want. When we get to the project itself, there's a lot more details there for you. Okay, so think about the noun in that product description on the previous page and just write them down on a piece of paper and maybe give us a minute or two of thought as to how they're related. For example, it said the player has a bunch of pieces. Okay, so then you know you can draw a line from player to peace or something like that to show that they're related. So what you should do now is just pause the video for a moment. I'll go back to this slide posit right here. Take up no more than a minute or two to think of the noun ends in that loose requirements section and write them down on a piece of paper, maybe draw some lines of like how they might be related. Okay, so pause the video and when when you're done, go ahead and start it up again. All right? Hopefully you did the exercise, and here they are, the ones that were going to be using. So hopefully you came up with some of these. First of all, there's a top level concept of the sorry game, right? The game is played by players. The players have pieces. The the game has a bunch of squares. There's a deck of cards, right? We have all these different things. I've strategically chosen the concepts I put on this slide for the ones that we're going to need for the project. So, for example, you might have come up with a board because the game it has a board that has the squares air on the board. Turns out when we write the code, we don't really need the board class. It kind of gets in the way. So I just removed it here. So I'm cheating a little bit, right? Um, a couple of points about this model here. First of all, it's only partially finished. We're gonna keep working on it. It's a model of the concepts of the requirements. Right. So this is what we call a conceptual model and the things like peace and square and card. Those air concepts and the notation were using is called UML the unified modeling language , which is kind of just the standard way that we have, you know, pre defined modeling notation to make models of software systems. So if you're going to draw software systems with boxes and arrows and lines and things like that, you should use UML because there's a standard meaning to the, uh to all the elements of the diagram. Okay, so what we're doing here is called object or in analysis, which is generally followed by design. So what's the difference? While analysis is about understanding, your requirements and design is about okay, how we're going to build the software. They mesh together really seamlessly, which is a wonderful thing about object oriented software development, but also causes some confusion because you can confuse the analysis for design and vice versa. If you're not careful, um, this whole discussion about object or in analysis and design, O and G, as we call it, It's huge. It's fascinating, um, love to dive into that. But this class is really about Java, so let's not get too far off the track. Uh, we're taking a lot of shortcuts through the analysis and design pathway so we can get to the job a part of the of the class. So if you're interested in this Sorry about that. There's plenty of references out there. You can go read about this, but let's get back to Java here. All right, So how do you code a class? Well, we've seen this before. The basic outline of a class looks like this public class, and then the class name and then curly braces where the code goes. All right, um, public is called a modifier. There are other modifiers besides public. Don't worry about them. Now, let's just do public Well, just this is the most by far the most common one, and we'll just keep doing this. All right, So now we're ready for the first exercise. So we're going to go into the I. D. E. We're going to create a new project called Sorry Game, and we're going to go through each of the concepts on our little diagram that we had in the slides and we're gonna create a class to reach one of them. At the moment, we're not gonna hook them up or get them to work or do anything like that. That will be in the next section of this chapter. But there's three more sections to come, so don't worry. We'll get we'll have it working by the end for the details. Looking your exercise instructions. Once you're done with that, ah, you can come back. And just following this slide, I'm gonna work through it myself on screen for you guys. So you guys can take a look and make sure that you understood everything and then we'll move on to the next section about attributes. So pause the video right here. Go ahead and do your exercise. When you're done, you can resume the video and you can watch me do it. Alright, let's try this exercise. So here we are in the exercise book for Chapter six, and the first section here is about the requirements of the game. So I hope you read this because there's a lot more detail here. I'm not going to go through it with you. You can easily read it. Uh, also the simplifications. A really important. We're doing a lot of silly things right now. Like only one player, only one piece, only one card, only one square kid. This is a little bit ridiculous, but in the next chapter, we will be fixing that up in the next several chapters. In fact, um, let's move on. Whoops. Sorry. Let's move on to exercise a. I want a little bit too far here. Okay, so it says creating new project Ingrid's I d called. Sorry. Game. All right, so let's go do that. I will say and eclipse. You can right click everywhere. There's context. Ming is new job. A project. Sorry. Games. I don't want to put in a space there. We got job 11. We don't want the module info again. Put that out and we can open this up and there is our source Director. Great. Um, okay. Uh, we're going to start creating classes. So let's create these classes or some advice about. We're trying to stay out of the job a nine module system for now, because just the pain. And so we want to put everything what's called the default package. Hopefully, your I d will allow you to to do that. If not, if it insistent you adding a package name used the name game and then we'll talk about packages later. Okay, let's create these classes. Sorry, Game square player. Let's start with that so I can just right click here saying New class C. Sorry game. Now we don't want to add a kind of a main method this time, so leave these unchecked. All right. Sorry, game player. Let's see what the other ones are. Square piece. Since do those will do this one will go square. Will go piece, decadent card. Onda car. Great. Okay, so says we don't need to add any further code, will come back and do that next. So one thing the only thing you need to be sure of is that there's no Big Red X is anywhere that says that the code can't compile all right, and really, that's it for Section A just was to get these classes in place. Now notice again. These are the concepts from the requirements document these air. You know, the game, the square, the player, the peace like these were things that we wrote about when we started talking about the the requirements of the game. And that's kind of the essence of object orientation. So, so far, your program doesn't doe do anything because there's just a bunch of outline. Classes will be fixing that up in the next few sections. All right, that's it for this section will see you in the next section, Section B. 8. 06b Objects Attributes: Okay, welcome to the second section of this chapter, which is section B about attributes. So it turns out that an object orientation classes can have attributes, which represents data that belongs to the instances of those classes. So what do I mean by that? Well, let's look at the idea of a card. The class card are sorry. Game simulation has cards in it, and each of them have their own unique value. And the value here is an integer. That's what the I M. T stands for. So in other words, value is a number like 12345 and each card has a value. So in the class diagram still, we're back it analysis. Here we can mark that down by giving the class card on attributes called value. And then after the colon is the type which is imager. Now what exactly does this mean? So we have to understand the difference between classes and objects. This is really key in object oriented programming. The classes represent blueprints or factories for creating objects. Objects are also called instances. Now. Ah, the word object is a little bit overloaded because we have object oriented programming you have lots of things that people call objects. The word instances a little bit more precise about what we're talking here. So I'll try to use that word instance. But forgive me if I say objects sometimes. What's the difference? Well, a class we've already written some classes there in source code, Right. You opened up an editor and you typed in public class player. Curly brace, curly box. Okay, that's a Java class. Doesn't do much yet, but it is a class. These air source code, uh, constructs. Where are the instances? While the instances air not created until you run the program so they exist in the memory of the computer at runtime, they don't exist in source code. Right? So you have one class of the given type. So you wrote public class player. That's the only file you have. That's player dot java that has a public class player. Right? But at run time, when we run this, I hope our game can have more than one player eventually, because otherwise it's pretty boring. We know who's gonna win, right? You can have a quote unquote unlimited number of instances. Of course, if you think about it. If they exist in memory of the computer, then you can't just create an infinite number because you'll run out of memory. But there's no fundamental limit on the number of instances that can be created from your one class file. The class file defines the attributes like we saw a card has a value or down below. We see that a player is a color you know has a color. So, like you have the blue player, the green player when you're playing Sorry, eso That's the definition of the attributes, The class file says. Every player has a color, but it's the instances itself that have a copy of that attribute and have its own unique value. So here's a little bit more UML. Don't worry too much about the notation. It's just a convenient way of note dating it. But on the left, we have the class diagram with the class player, and we say every player has a color, and that color is the string. It's just some letters. Um, that's sort of the, uh, the abstract layer. You know, the player is a concept at run time. We're going to create instances of players and they've been named here player, one player to player three, and they each have their own color. So Player one has the color Green Player two has the color red and player three has the color blue. Those of the attributes doubt, values. So just to talk a little bit about the notation, just so it's not super confusing. You see how like player one here is underlined. And, uh, then it says colden player. So the underlying in, um el that indicates this box represents an instance or an object at runtime. This part of to the left of the colon is the name of it, in case you want to talk about it and say, Look at player to okay which ones? Player to while this one is named player two. On the right hand side of the colon is the class that it comes from. So we're saying that this instance is formed from this class definition, and then, if you like a little line, you can say OK, here are the attributes that the class defines and what value they have. So the player that we're calling player one has the value G R. E E N For the color attribute in the player class, the player three has the color attribute value of blue. All right now, as we go through this chapter, Will Seymour about this about how to create instances how to assign them. They're attribute values. You know, those might be questions you have right now, but we'll get to that. Don't worry. There's a lot here. Teoh Impac, now the player having an attribute of type, color of color of type string. That's what we call a simple attributes. It's like, you know, if you have a string or a number or Boolean or something like that, those air simple attributes. But what's really interesting an object orientation is that classes can have attributes better other classes. So while we're still doing analysis here and we'll get to the code in just a minute, the way we denote that is by drawing a line between the two concepts and saying, Yeah, there's an association there. There's an association between players and pieces, you know, players own pieces. Pieces belong to players like there's something there, right, and this is gonna work its way into our source code. Those lines on the diagram. Sometimes they have numbers attached to them. You may have seen that those numbers are called multiplicity ease, and they have a specific meaning. So from the point of view of the player, this line going down here to peace ends with one dot dot for and what that help you read, that is, a given player has somewhere between one and four pieces associated with it. And if you read the other direction, a given piece is associated toe one player. All right, so it's just a way of keeping track of how many of these things there are. So before we talk about how this translates in the source code, which will be, you know, the next slide, let's pause for a second here. Go back to the conceptual model we drew earlier in the slides, and let's add the attributes that irrelevant. So we've already talked about cards, have a value, and players have a color. There's probably a couple other concepts in there that have interesting attributes. Um, when you do this, you can kind of go crazy on this. So stick to what matters for the game simulation. For example, here's a good example. In real life, a piece in the sorry game has a height and await and things like that. Nobody cares for our game simulation, right? If you're building riel. Sorry, games. That's very important. If you're simulating them in a computer, nobody cares how Told the pieces are right, so you can ignore stuff like that. And then once you've done sort of the simple attributes, then think about how the concepts are associated with each other. Which ones belong to what? And, uh, draw those lines drove. This multiplicity is in the same way that the piece belongs to the player. So just pause in my talking here for a second to give you a chance to pause the video, and you can go back and look at the that that diagram and maybe take a few seconds to add it at the attributes on when you're done, start the video again and we'll just review it right here. Okay, Hopefully, you took a few seconds to do that on your own. Here's what I came up with for this diagram, right? So in terms of simple attributes, we said the card has a value that's an ent. The player has a color. That's a string. The squares have a number. So as you go around the board, you know the squares are lined up in order square number ones where Number two square number three. So it's nice to know which square is which. So I gave them a number. I also gave the pieces in number. No player has four pieces or between one and four pieces according to our model. And really, the pieces air interchangeable. But they do have some kind of identity, and the reason I put the number in the piece is so that is really what we'll see as we build this project out is, I'd like to know when a certain piece lines in a certain square. I'm gonna print something to the console that says Peace number four for Player Blue landed on Square 14 and it's nice to have that data to be ableto right those debugging statements so that we can see that things were actually working in terms of the association's. Hopefully, it's not too surprising that deck has a bunch of cards and the cards are in a deck. Um, the sorry game has a bunch of squares there. 60 in the case of sorry. And we've got between one and four players playing the game. And we know already that the player has 1 to 4 pieces. Now. Another interesting one here is that the pieces are supposed to be sitting on a square somewhere, right? So every piece at any given point in time, is sitting on one square. The squares by this diagram can have star pieces. That means any number storming zero to infinity. No limit. In a real sorry game. If one piece lands on a square that another piece occupies you, knock them off and send them back to their home. We're simplifying our requirements here. We're just gonna let any number of pieces sit on a given square. That would be something fun for you guys to work on after the after the class is over. If you want to generalize the model toe include things like that, uh, in you could say there could be an argument made to say, Hey, all of this belongs to the sorry game, including the pieces in the cards. How come there's no lines there? Yeah, you could, um, getting into the details of objectivity analysis. Again, it's a little bit beyond the scope of what we want to talk about here in general. I'll just say it doesn't really do you a lot of good to create a concept like a game and then just drop, eat, draw lines to every other concept on the diagram. That's really not helpful, All right, so we try toe, emphasize the ones that are strongest, yes, the pieces of the part of the game. But they really belong to the player. That's more important then the fact that they're part of the game. All right, let's get to the code, right? So how did these attributes look like when you write code? Well, let's do the player class. So we've been looking at the player class. It's got a simple attribute of called Color of Type String and the way you write that here is, you say, private string color inside the class definition inside the curly braces of the player. Now there's something new here is this word private. Let's defer discussion on private. There's also public. You could also just leave off this modifier, but in general it's very, very common. Probably 90% of the attributes out there in the real world are declared private, and that's a good default place to start. That's how I always make my attributes until someone, something tells me that I need them to be something other than private. So let's just make all our attributes private for now. And later on in the class will go back and you know, we'll talk about private public and other modifiers that we have. So then the other one that we have in there is the piece. So notice how we said we had this, Uh, we had this association line between the player and the peace, and we said that Well, this what this means is the player may have an attribute of type piece and or the peace may have an attribute of type player. And here we've gone in and given the player on attributes called Peace with the Class name piece. So now noticed there's a capital in a lower case here. This is very common in, especially in Java, the capital P represents the class piece, right? The little P is just the name little P pieces, just the name of the variable, and we could have called this anything we had called it just p or P one or any other name that we want to use. But it's very common when you only have one. At this moment, remember, we're simplifying on this first round that we are only going to get the player one piece, um, to just say private peace, Peace. Just call it peace. Some people say the peace or its peace or something like that. I'm just gonna say peace here now. We've made a decision here that the player has an attribute of type piece, and that's called giving the player visibility to the peace because it can quote unquote see the piece. In other words, it owns this reference, this variable piece, and it can therefore talk to the peace, which we'll see in the next later on this chapter that that means you can send messages to it. So what's this visibility thing so the player can see the peace? But can the piece also see the player? So this is where you start to move from again. From analysis to design and analysis. It's good enough just to draw a line and say, Yeah, those two things were hooked up. Somehow in design, you need to know because, as we just saw on the previous page, if they really haven't attribute, you've got to write the code, right? So it's not just enough to draw a line. You gotta actually decide where the code goes in general, when you have circular visibility. In other words, the player sees the piece, and the piece sees the player. That's generally to be avoided, not because there's anything fundamentally wrong, but just because it can lead to complexity and some problems that, um, that maybe it's just better to avoid. I think in general it's It's things were simpler when visibility kind of flows in one direction. So, uh, for the purposes of our simulation, I'm just going to tell you that piece doesn't need visibility of the player, and only player needs visibility to the peace. So, on a design diagram, you start to add these these little arrowheads, and that tells you if this is a software design diagram, okay, the player has an attribute of type piece, but the peace does not have an attribute of tech player. If it did. It would be a double headed, double headed arrow here, which it's not right now. How can I justify that? Well, I cannot write. All I can say is that I built the project before I've gone through it, and I didn't need the peace to be able to send messages to the player. I didn't need the peace to see the player, so we're gonna trim that down and just have the player CIA visibility to the peace. One last thing about attributes before we go code him up. They do have default values. So when an instance is created from a class and we'll see that very soon, uh, the attributes must all have specific values. And so if you don't assign them a value, they obtain their defaults from the Java virtual machine. And what of the defaults? While numeric types like injures, longs, floats, doubles, those kind of things are set to zero Bull Ian's. If you have like a, uh, on the right hand side, you see private bully and happy, which is true or false, that will be set to false and anything else. That's a reference to a class. In other words, capital letter here. Right According to convention Ah, string is a class, so this name would be set to know. So what does know mean? No is a special? I guess you could call it a key word in Java that denotes the absence The absence of an object so that that variable name is supposed toe contain a string of letters which is the name of the person. But we haven't assigned it the name yet. So it just has the name has the value know which says there's no string there. There's nothing there, right? One quick note. These default values only work for classes When we get to methods later in this chapter, if you define variable in the method, they don't get these default values. Oddly enough, they take on this very this value that is undefined, which is really a compiler error if you try to use it before you to find it. All right, let's just do the exercise now for the attributes. So go back to your project and add all the appropriate attributes to our classes again For the time being, until we can study about a raise and collections and things like that, we're gonna assume there's one of everything. There's one player. There's one piece in fact, rooming in. Assume there's only one card and one square, which is kind of ridiculous. But just to get the game working, and then we're gonna generalize that really, really quickly. So check your exercise instructions that has the exact instructions. And I'm gonna pause speaking here for a minute. You guys can pause the video, go do your project, and when you're done, come back and start the video again and we'll take a look at how the solution might look all right. Well, hopefully you had a chance to do that and work on your exercise. Let's go take a look. So when we go and look at this in the in the, uh, instructions for the exercise we had this section exercise. Be attributes and you see here what's there's a line missing there never had missing. But we see here that the our heads and the multiplicity is have all been adjusted for this project. OK, so let's go ahead and start with the player because that's the one we were talking about in the slides. It's got this string color, and it's got one piece right now. So let's switch over to eclipse and let's go to the player and will say private groups, string color and private piece peace. All right, let's get back here and will say, Let's go to the peace will. It has how many attributes while there's the number here. But then there's also the square, right? So let's go to peace. And there's something interesting to say here, prove it and number. I believe that's what that was called, right? Yeah, and now there's it has another attribute of type square, but there's no indication what the name of that attributes should be right, So we could call it square in accordance with the way that the players pieces just called peace. But actually, I think in this case there's a ah, better name because what is the square that belongs to a piece? It's the location, the current location of the peace. So the pieces sitting on the board somewhere at all times is, uh, unless it's being moved. It's sitting on the square, and that is the pieces location. So I'm actually going to call that variable location. It's not necessary. Of course, you could name it. Whatever you like. The square itself has. How many attributes? Well, there's the number and there's no outgoing arrow. So the square only has one attribute called It's Number. That will change as we go on. But let's start with that private number. It's like I'm square number one square number two. Uh, the card has one attributes its value, which we talked about also in the slides. Six. Private, I tell you, the deck now again for this humbled version, first version of the of the project. The decks only gonna have one card, which is kind of a ridiculous thing, But let's do that for the time being. Private, hard card. And then the last thing is the sorry game, which has a player, a square and the deck, even though there should be an arrow here which got dropped. But that's OK, so we have a player, private player, player, right, but that deck in private square. All right, so now notice that in eclipse it's already warning you. It's like what's going on? It's a swell. You've defined this field called Player, and you never used it anywhere. It's like, Yes, that is correct. In the next section or two of this chapter, we will start using those. So by the end of this chapter will have a running simulation going. It's gonna be boring because there's only one square. So we always know where the pieces that's on that square. And we always know the winner because there's only one player. But we will get to that very same. So that ends the chapter. For attributes, stay tuned for the next section. 9. 06c Objects Constructors: All right, welcome back to the next section of this chapter, which is about constructors. How to create instances from classes. So, so far, the problem that we got is we're trying to do object oriented computing without any objects . So simply declaring a new attributes like player like in the sorry game we have private player player. Creating that variable does not actually create an instance of the class player. It simply is like a slot toe hold onto a player, or it's like declaring your intention to create a player at some later time, So that's no good. Well, how do we actually create instances? Well, we use this operator called New. This is a special keyword in in Java, which creates an instance of the player takes what we call a reference kind of like the address to that player and stores it in the variable that you're assigning it to like the variable player. So you can say is, you see here player player equals new player. So a lot of players there, but the new operator, followed by the class name and then a pair of forensic, and that indicates that you're creating a new object. Or to be precise, you're creating an instance of the of the class player right now. You can call this new operators many times as you like. You can a player one player 23456 as many times as you like to do it until you run out of memory, as we talked about in the previous section. All right, so when you in Stan, she ate an instance. When you call the new operator and create an instance, what happens is the JBM will call a constructor on that class, and that allows the instance to initialize it state. So we talked about default values in the previous section. You generally don't want the default values. You want real values, right? So you what, you want to actually fill them out? So when you call this new operator on the class player, it's going to call this method here, which is a constructor. Now. How do you know this is a constructor? They have a very particular signature here. Generally, we make them public. They don't have to be, but for right now, let's assume their public. Then they have the class name, followed by a perent. Okay, so, uh, it's a little bit different than other methods. Signatures? As we'll see in the next section, there's no return value declared here. We haven't actually looked at other methods in detail yet, but we'll see that in a minute. And so what can you do within the, uh, curly braces of the the constructor of the player class? You can. Generally, what you want to do is initialize the state. So what does that mean? So we have this variable piece, and just like when having a player doesn't mean that we have a player. Instance we don't have a piece instance here either. So let's create one with the new operator. Right? So I'm gonna call New piece. I'm going to sign that value to this variable piece. And of course, that's going to call the constructor on the peace class and so on down the line. One thing to notice here is that this is what's special about the attributes of a class is that within the methods of the class, including the constructor, you can actually read and write these variables. They're kind of like global variables inside the player class, right, there private to the player class. Nobody else can see them. That's part of what private means. But from anyplace in the player class, you can actually talk to the color. You can talk to the peace. All right, well, looking that a little bit more as we go along. Okay, so a constructor as we've seen it so faras, you know, useful. But it would be nice to be able to pass some data in. So, for example, in our game, eventually we're gonna have a player, a red player, a blue player, green player, yellow player. How do I get that data into the player? Instance? Because I can't hard code that in the constructor, because I can only type one color when I make the constructor. So what I want to do here is when I stand, she ate the class instead. She ate the instance. I want to be passing along the color as a parameter. Right. So by when you say new player and then within those parental, you can put parameters in there. Those parameters will be passed to the constructor here. And so you see that, um, you know, we have public player and now we put some parameters inside the constructor call. And so what we can do is now we assign the color value that's passed in which he called the color and we assign it to this color here. And then we created peace instance like we did on the previous line. Okay, so that's really useful. You can actually have multiple constructors in a class. You can have as many constructors as you like. They do need to have unique combinations of parameters. So here we have one constructor that has no parameters. This one takes a string. You could have another one that takes two strings or three strings or a string in an integer or two integers in a string or any combination. As long as that's unique. This one is special. This is the default constructor because it takes no arguments. And what does it mean to be special? Well, if you don't write any constructors in your class, the compiler will add a default constructor for you. Basically with an empty body between the curly braces. Okay, so it'd be like public player, curly brace, curly brace with nothing on the inside. However, if you start to write any constructors explicitly. Like if you type into your source code any constructors like this, um the compiler will not added default constructor for you. So if you want one, then you you have to type it in. You actually have to add it, right? So either don't write any, in which case you get default one for free or if you're gonna type any of them have to type them all, including the default constructor. Now, why would you want to have multiple How would that be useful? Well, you can chain constructors, and this is something really common that you'll see. So, uh, this is a way of avoiding duplication of coat. So when you call the default constructor, maybe you want to say, Well, you know what? If you don't pass in a color when you create a player, we're just gonna assume that it's great, right? So in the default constructor Aiken, put the default right. Like I say, I want to have this color be gray. But the way I'm going to do that is by calling the constructor that actually takes the color right. So when you're within the constructor and you. You write a method called that Looks like this and use this keyboard this and then you pass parameters to it. What that says is called the pretend that they actually called this other constructor with this value. Right? So this statement here that says this actually calls this constructor and passes in the value gray, so it it assigns greater color and it creates a new piece. And so when you have lots of or not even launches being in multiple parameters, that can be passed to the constructor and a lot of them have default values. People do that by writing these default constructors and use are these constructor chains and passing the default values along like that. All right, so we now have to go back to our project and start adding the constructors. And there's detailed instructions in the project booklet. And once we're done with that, the next thing we'll do is methods. So first of all, um, go ahead and pause the video. Here, go do your project, and when you're done, I'll walk through it with you together so you can kind of compare notes on how you did it and how I'm doing it and then in the next section will get onto the methods. And at which point, we'll actually be able to run the simulation, so that will be great. All right, Hopefully you've got a chance to do your project. Let's go take a look. So I'm going to switch over here to this section. So this was roll up a little bit here, Section C, the constructor exercise. And, uh, there's some detailed instructions here of how to do it. So let's kind of do that. Cards have value, but what value? Some of them a one some of them are to. Some of them are three. So we're gonna give that responsibility to whoever is creating the cards to tell them what their value is. So let's open this up good to our card, and we're gonna put it constructor in here. So we're gonna save public card. Remember, when you write a constructor, you use the keyboard public and the name of the class, and it said to pass in the value, so we're going to say it and let's just call it a value. Ah, and will say value because the value All right, So now what we have now. We don't have a default constructor here, right? Because I've written a constructor without reading a default. So whenever you create a card, you have to pass in the value. Otherwise, you can't create one. Let's go back in the deck. We have to create a card. And remember, we're just doing one for now, so there's a little bit hokey, but let's pick a value. Let's say the number three and creating new carts. Let's go into the deck and will create a constructor for the deck public deck. Now this is a default constructor, but we're not going to leave it to the compiler because we got work to do here. We got to do this rights recreating a card with the value. Three. We couldn't let the compiler just generate the default constructor for us because we have some specific work we're doing here that you know, the Java compiler wouldn't understand that it's supposed to create a value Ah, card with the value three. Right? So I had to do that ourselves similarly at a square and at a constructor to the square and the peace. Now the piece gets two parameters on injured for its location. I'm an integer for its number and a square. That's its position or location. So let's do the P uh, sorry. Were those square in the Peace of the Squares? First Public Square on. We're taking it into value here, and we're saying, Remember those values? Um, I can name this parameter whatever I want, but I've kind of been doing eso. Here's a little trick in eclipse. There's a re factoring you can do. I'm going to shift all our and I say, Let's changes to the number Notice how it's changing it at both places. And when I had enter its renamed it at both places for me. So that's a cute little tool. You can use the peace. Okay, so it says at a constructive It takes two parameters and called number in a square called position. So I called this location here. I misspoke. It should have been positions. Let's just change this before we get too far down the world road. And let's get this constructor going. Public peace and how it takes two variables that int number and square the position and will say remember, he calls and position was was it all right? Okay. No, In the players case, we need to know its color and create its peace. So there's a little bit of a discussion, or this is actually an interesting discussion. So, uh, piece constructors need to know their number, which is fine, But they also need to know their position for this square. So it says in order to in Stan, she ate the piece. We need a square to pass that the constructor in requirements, terms the player needs to know what square to put his piece on at the start of the game. Someone outside the player needs to have this knowledge because clearly, players are not in charge of squares. So let's just add a parameter to the player named start square of type square. So this basically advertises to other people. Hey, someone needs to tell me where I'm going to start my pieces, all right? Peace also needs a number right now. We'll just do number one. Right. So we're gonna do something like this. So this is a little bit more complicated. Kind of an interesting thing. And let's talk about this use of the keyword this in the in the constructor. We talked about that earlier in the didn't really talk about that. So let me talk to you about that a little bit here. And let's actually just change what we have here. So I've been calling these things, putting the on so we don't have number equals number. But however, using my little re factor tool again, this is illegal, right? So you saw that it came up and it's a name collision. It's actually not illegal, but it's a little bit curious here, right, We've got into number here. We've got a number here, and then we have number equals numbers. Like what in the world is going on? Uh, in general, when you have multiple variables, we have number here and you've number here. The one that's closest to you takes precedence, right? So what we're saying here is that we're just assigning number two itself, right? The assignment to variable number has no effect, cause we're saying number equals number and it's this number. How do I tell it that I'm that for this one? I'm talking about this number, right. So what you can do is say this dot number, and that qualifies it. You can do the same thing here. This that position, maybe just leave it like this. This is also legal. Um, but when you say this dot what it says is I'm referring to the variable. That's that's actually an attribute of the class. Okay, that one that's up here. I'm not talking to about any local variables down here. So when you say this dot this is a special notation that you can use in Java to refer to the attributes that you have out here. All right, so now we're going to do the player, but for the player, in order to create a piece I needed, I needed starting square. But I don't know any starting scores as a player. So I'm just gonna punt and say, You know what? When you create me, you gotta pass in a start square. So let's let's write it out. Maybe this will make some sense. So, public player, I need my color, which is a string. And then I need someone to tell me when they create me when I'm born, I need to know where to put my pieces. Right. So this dark color equals color. Right and again you can see by the way, eclipse colors, the colors, the colors, colors, the variable names. This one is blue. Can you see that? That's blue And this one is blue and this one is brown and that one's brown. So it's trying to tell you. Hey, this color refers to this color, but this one, because you put this dot in the front, actually refers to that one just kind of interesting. And then this dot peace equals a new piece. We're going to create ourselves a piece. It's our first piece. We just call it one, and then we have start square here. So if you just saw that I have made eclipse AutoCorrect for me, you do that by pressing control space, right? So this is a little bit of an interesting construct here in our player constructors. Someone's passing a start square. I don't actually hold on to the start square. I don't assign it to any of my personal attributes. I pass it on to my piece. This kind of an interesting design. It's not unusual, and it's not some. There's nothing special about it. It's just a different way of doing it now. The use of the this dots, we weren't doing that in the beginning as we went through. But this is actually quite common in Java, and I would say Personally, I would say there's a pretty good habit to get into So we could go back and say the stock value Now we can leave it like this and we need to say this, that value because the value it is quite common for people to give it the same name because the values kind of a wonky thing to say right. So my shift all toe are once again to do re factoring or renaming Rather, and I change it to this dot value cause That's an extremely common way for people to define their constructors. So it's really good for you guys to get used to that. All right, Do we have anybody else now? The sorry game. Let's talk about what it says here. It's has a default constructor that has to. In Stan Sheet. It's three attributes the player of the square in the deck, the decks easy. It's only the fault. Constructor. The square wants to have a number and since we've only got one square right now, one is a good number and the player wants a color. Let's just make it blue and it wants to start square. Since there's only one square right now, that's the only square. We have to be a start square, so let's try that. So we go to the sorry game public. Sorry game. This is a default constructor, and we're going to say, uh, this not deck of course deck. That's easy to say This square square. Now remember, Way Square has a number in It's constructor. Let's take a look at it again. It's constructor takes an integer. Here's what happens if you don't pass in the parameters here it says, Hey, you don't have a constructor Default Constructor Square. You need to add a *** like whoops. Yes, sorry. Let's put in the number one. Okay, now it's happened. Now the red line goes away and then the player because he knew player and we said, Let's give in the color blue and will pass in the square. Yeah, as the start square. Since there's only one square, there's only one place where they can start, and that would be that particular square, All right. I think we got constructors everywhere now. The deck, the card, the deck, the peace, the player, the game and the square. All right, So in the next section, what we'll do is look at adding methods and methods or where the work is actually done, and at the end of the next section will have a running simulation. 10. 06d Objects Methods: Okay, welcome to the last section of this chapter, Section D. We're going to talk about methods at the end of this chap section will have our simulation hobbling along. At least it will be doing something. Well, that's looked Let's just start again. Okay, Welcome to the last section in this chapter section D, about methods. So methods were where the action is, Right? So right now we've created a bunch of classes, so we have our concept lineup. Then we put some data in them in the form of attributes, and you know them up to each other. And then we added constructors so we can create them, and that's all great. But they still don't actually do anything. And methods are where the action is. Right? So what we're going to do here is talk about in this chapter of the structure of methods and method messages. So this is just a little bit of oh, terminology. So here I am, in some bit of code, I create a player and I say, player dot take a turn. We call that sending a message to the player object this little dot here says on the left hand side. It's the name of the object or the instance, and on the right hand side, it's the name of the message. What does that do? It actually calls a method on that class. So the player instance is an instance of type capital P player class. So in the player class, there is a method called Take a Turn. And then there there'll be some code that runs. Okay, so let's talk about First of all, how methods air written. The signature, which is the first line, has three different components to it. There's theatrics s modifier that's public or private. Then there's the return type, so methods can return values they don't have to. And if they don't use the word void there, so there's always something in that position. And then the third thing is the name of the method. Take a turn, which you congest make up the name to be whatever you want, and then in the parentheses, there may or may not be parameters that get passed in again. The beautiful thing about writing and classes that all the methods in the class can see the attributes of the class. So a player class has a color in a piece. So when you say take a turn, you can access the peace here. I'm telling the peace move six steps and you can print the color here. I'm printing or you can access the color here. I'm printing it out. A debug log, right? If the method actually does have a return value, so it's not a void in the second position, then you have to use the return key word at the as the last line of the method and say, This is the value that I'm going to return to Whoever called this method and we'll look at it a little bit more closely in a minute. Okay, First, let's talk about the access modifiers Right now. We were talking about public and private. There are some others, but these air, this sort of too extreme ones. And what does public mean? Public means that, um, code and other files can see that member of that class. So here we've got the method take a turn being public, And that means if you're in a different source code file, you can say player dot take a turn in that compiles just fine right with private. So here we have these, the color, the string color as a private attributes. If you're in a different file and you say, player dot color, that's not gonna work. Compiler is gonna flag that, and that will fail to compile. So for this starters, well, is the default position for most people is to make all their attributes private and make their methods public. And that's a great starting spot. And later in the class will talk about a little more sophistication around that. Okay, And then methods can take parameter. So if I want to tell the player to move six slots, I pass in that parameter when I call the when I send the message here. And that means in the method I need to declare that parameter hair manager called steps. And then within the code of this method, of course I can use the value that was passed in, uh, the parameter steps. We talk again about the this keyword. So again, if I want to be explicit about the fact that this variable piece is the piece that is an attribute of this class, I can put this dot in front of it, Uh, in this case, because there's not any other variable name piece the compiler understands if you just say peace that it's this one. But putting this dot is a makes it explicit that you're talking about this one. So here at this dot piece and this dot color in here, I'm returning this dark color depending on really personal style. Some people like to use this dot for everything, as as it happens to be in this file here on this slide. Some people never use this. Stott and other people use it say, only in the constructor, or only if there's some sort of ambiguity that they want toe make clear. It's really a matter of personal style. I think using that this dot is kind of quote unquote officially, what is recommended. But of course Ah, we developers are quite lazy, and we don't like to take this stop all the time. If we don't need to. Now, it can be helpful sometimes to make your code a little bit clearer. Here we have a method in the player class called Fight with some other player, right, so we're having them a little bit of gladiator style here, and the fight with method simply prints out. Hey, my color is read and your color is blue or whatever the colors are. So both players, both the current one and the one called other that's being passed in. They both have a color variable. So it's a little bit weird in this method cause you're referring to two different ones, so you can say this dot color and other dot color. Right and color, of course, is an attribute of the class player. So I'm within the clocks player. I can just reference it directly, even though it's private. Um, but then this dis ambiguities which color you're talking about, right? So that's a very good use of of the this keyword. And as we spoke about in the, uh, in the exercise for the previous section, you see this dot notation a lot, and constructors like this, uh, pattern that you're seeing here. Were you passing in a color? And the constructor simply assigns that to one of the attributes of the class that's extremely common, so you'll see this all over the place, and generally, if you're going to say this doc color, it's probably nice to say this stop piece just to make it parallel. This code snippet didn't but it is a little bit jarring to see this dot color and then just peace. And then maybe there's 1/3 1 1/4 1 If you're going to use this 10.1 of them, you probably use this dot all of them just to make it more readable. Okay, getters and centers air specific types of methods that access attributes Well, actually, it's not necessary that the access attributes, but they almost always dio, um, But if you write a method Andjaba that's get something and or set something, that type of a method is a special thing, and it creates what's known as a property. Now this idea of a property comes from a specifications called the Java Beans Specifications. Right? Kind of. You know, Java refers to coffee, and then so there's like coffee, beans, rain, um, and what this would mean like when you see public string get color, you're creating a property named Color Lower Casey with the type of string, and then the fact that there's a getter and a center means that this property is read right now. What in the world are we talking about here? Well, there's a lot of tools and libraries that work on this pattern. And there's a lot of, ah third party code that you can use out there where you say, uh, my player has a property color and its value is red and the code will actually translate that to mean. Okay, call set color on the player object impasse in the string. Red. Right. So, um, this is something You'll see a lot getters and centers or super common for the especially for attributes. And, uh, you can you don't really need both of them like you can have a read only property. So let's say, you know, for our player, we set the color in the constructor, right? Maybe we never want the player to change its constructor. So then there's no reason that provide a center. In fact, that would be bad idea to provide a center because some other programmer one day might actually set the color of an existing player, and you don't want that to happen. So don't give them a center right. And in really weird cases, you might have a right, only property. So maybe there's no getter, but there's only a center that that's kind of unusual, but I suppose it could happen. Okay, so that's the mechanics, the syntax of centers. Now we get back to our design question, which is like, Well, what methods? I'm sorry of methods. What methods should we write and what methods go where, and actually, this is really a profound question when you start looking into object oriented design. Generally, you should put methods in the classes that have the data necessary to fulfill the method. That's kind of the point of objects. There is a set of patterns called the grasp patterns. It stands for general responsibility, assignment software patterns. You can go look those up online. This particular sentence here is called the expert pattern from that list of grass patterns . Uh, this is not part of this class. I mean, we're really trying to focus on the job a language, so we're not going to go into this. But if you want to learn a little bit more about design, that's a great place to start now, because this is a kind of a deep question. We're going to go through in the slides where the methods for our project go so that before you go to code up the game, it's not a complete surprise or a complete mystery. How this is done, right? So there's a little bit of um, el. You might see some of this in the in the slides or in the, you know, the following slides or in the in the exercise. So here we have two boxes, a game called sorry game and a player called Player One. And the boxes are represent instances, and we know this because they're under the label is underlined in the UML. The label me the underlying means. It's an instance, right? We see they're connected by a line and there's some kind of thing here. Take a turn that sliding along the sign with the direction of the era. That is a message. This is saying the game is sending a message to the player called Take a Turn. So what in the world does that mean? So somewhere in the sorry game, we can't tell from this little snippet, but somewhere in the sorry game class, it's saying player not take a turn because actually should say plate, to be perfectly consistent. That should say, player one here in saying Take a turn. And then, of course, we know that sending a message to another, a knob checked of class player is going to call the take a turn method on that class. So this is the UML syntax for sending a release. One of them. There's multiple sin taxes for showing methods being called because again, the methods and messages are really that complicated, part of of, ah, hello design. So when you execute a class in Java, it starts with the main method right? But where should we put the main method? Because we can kind of put the main method wherever we like. And generally there's. There's a couple choices that you think you'll see very commonly. One is some people will create a class called Main simply toe host, the main method or the creative class called application or runner or something like that, and they put the main method in their or they'll use some sort of top level class. So, like an hour a project, we have this class called Sorry game, which is clearly like the big class. That sort of owns everything and is thean since of the game itself. And so we can, just for our purposes. So we want to create more classes will just put the stat the main method into the sorry game. So what do you do in the main method with a complicated, you know, a little more complex application here where we have multiple classes. Well, you create some objects, and then you get them going, right. So, uh, again, Sorry. Game here is playing two roles. One is that's where we're gonna put the main method. Could be anywhere, but makes sense to put it there. That's a good place, Teoh. Hide it. And then the sorry game object or the sorry game instance is going to be sort of the top level, the root of our hierarchy. It's the big the big parent class. So we're gonna in Stan. She ate a sorry game object and we're going to tell it, Teoh, go or play or execute or run or begin or, you know, some kind of method like that on the sorry game class. So here in this code snippet, we're creating sorry game, and they were saying Gamed out play. All right, that's a reasonable because we you know, you generally say you play a game, so probably play is the best method name. And of course, that means on the sorry game somewhere else in this file. Because this is the story in class, you would need to create a method. Coldplay. So what happens in the play method? Well, players take turns in rotation, and they would each do whatever players do when they take a turn. Now, right now, we only have one player, so let's have them take five turns. And so here we go. Are four loop that we learned about before. J is the loop counter. So we go from 0 to 5 and we say player dot take a turn. Oh, note that the method name changed from play to go here. Sorry about that. So what happens when the player takes a turn? Well, you got to do these kind of things. You got to get a card from the deck and then move your piece along the squares. That many in numbers. Right. So right now we're just considering all the cards. Just moved the peace forward later, we'll do some more interesting things. Okay, so we have some problems here. First of all, the player can't see the deck. It has no visibility to the deck, right and ball. So who does well right now? Only the sorry game has visibility to the deck. But remember previous slide. The sorry game is the one who is telling the player to take a turn. Right? So since the game has the deck, it could actually pass the deck to the player when it says take a turn. So we'll see that in the next slide. How that works. But the other thing is the second part of the players. Responsibility here is also really challenging. How do you move the peace? Um, the peace knows its own current location, right? We put that down, and, uh, the card knows how many steps to me, right? So we need both pieces of data in order to complete moving the peace, and so we have to have one of them do it. And which one should we have? Do it. It's a good question. So when the game plays and says player that take your turn, we can pass in the deck. So we kind of modified this to say OK, pass in the deck here to the players of the player now has the deck, and I can draw a card from the deck. So let's put a method draw on the deck and returns a card. And now we we between the card and the peace, we can figure out how to move the peace. And so we could either say have peace, take charge and passed the card in as a parameter or because the card take charge and passed the piece in as the parameter. We're gonna have the card take charge kind of arbitrarily at this step. Just because what we're going to do in later chapters will be easier and more interesting if we do it this way, instead of passing the piece into the cart. So once again, I'm kind of using future knowledge toe to make this design decision. Okay, so we just invented piece dot move decked out, draw um, again in the deck. Drawing the card is easy because there is only one card, so you just return it for now. That will get more interesting in the next chapter. Um, but moving a piece is weird because there's only one square like you're supposed to change the pieces position, but, uh, we don't know how to do that, because there's only one score. So for the time being, when you tell the piece to move a certain number, we're just gonna print out. Hey, I'm on this square and get the get the number of the square and just print that out, OK? And then again in the next chapter, when we had multiple squares, well, actually, have the piece moving around. That'll be a lot nicer, all right. With that introduction, it's time to go and do the do the project again. There's detailed instructions in the instruction booklet that will show you exactly what to do if you if you kind of get stuck and at the end of this, the game should be running it. It's not interesting again, cause there's only one piece, one square, one player, one card like it's kind of boring. But in the next couple of chapters, we're gonna fix that up and make it way more interesting. So go ahead and pause the video. Now go do your exercise and when you're done at the last half of this video will come back and work the project together. Okay, hopefully you had a chance to go and do that exercise. Let's take a look. So here's the exercise booklet and it starts with what we said before. Let's add a main methods of the sorry game. Create an instance and tell it to play. All right, so let's go over to our lips. Need to go to eclipse. So we said we're gonna put the main method in the sorry game now, generally and again, this is sort of just convention. The main method goes at the bottom. So public static boy may remember we talked about this long and can't ation here arts. Okay, so who cares about all that? But what we're gonna do is say sorry, game game, because new Sorry game. And we're going to say game. I doubt play. Okay, couple things about this. So first of all, some people get a little bit confused about why am I creating a sorry game inside the sorry game class like that's a little bit weird. Remember, when you have a main method, this is um, this is what's called a static method, and we haven't talked about statics yet, so we'll get to that later. But really static methods air kind of like they're kind of like floaters. They could be almost anywhere we could create another. As we said in the slides that could create another class here called the main class and put the main method there. Or I could, you know, put it. I could put this method in the car to classify wanted to. That would seem odd to me, but the compiler wouldn't care, right? So even though the main method is inside the sorry game class, it's sort of separate from it. Second thing that's interesting here is as soon as we type this, the compiler says. Yeah, you screwed up. It's got this red line here and saying, You know what you're doing is wrong. Well, that's because we're kind of we're implementing this from the top down, and so as we type in our new messages here and we're sending the play message to the game instance, we haven't written that method yet, So the compilers, already looking ahead and saying Hey, there is no play method. All right, What? We're gonna do that. So it says Sorry. Let's get back to this and says Okay, now we need to add a play method where we tell the player to take a turn and pass in the deck. And we talked about that in the slides. Now, uh, the game is an instance of Sorry. Game. So this is the correct file to add the play method. So let's do it public. Boyd play when you play a game, What do you do? Well, for the moment, let's see. What letter are they using here? I zero. I bless them. 55 turns is enough for our game right now. You could always make that more or less in the future. And we're gonna say, Player, we only have one player take a turn, and we know from talking through the design that they're going to need the deck. Right. So we see that here we say take a turn. They said, Just take turn. Okay, let's take the boat just to stay consistent. Okay, so we tell the player to take his turn, and here's the deck of cards. So we passed the cars to the player and say, Take your turn again. The compiler gets mad because this is you don't have a take turn method on the player. And yes, I understand that we haven't done that yet. Okay? So let's go to the player and let's do that. So we're gonna add to take turn method. The player draws a card and tells the piece to move. All right, so there's more discussion of it in there at won't just read it to you, but public blade take turn, and we're passing in the deck. All right, so we wouldn't draw a card from the deck. Oops. People's deck. God draw another method we haven't written yet, so it turns red. And now I want to tell the the I need to move the peace, and I need to know the pieces location, and I need to know the cards value. So somehow I need to mix those two guys together and get them to do the work for me. Um, you always want to be lazy, An object orientation. I don't want to do the work. I don't want to, like, get the position and the value of the card and figure it out for myself. I want them to do it. You think you're the boss, right? You don't need to do the work. So, um, we can either delegate to the piece of were the card in this case again, we're going to say, Let's delegate to the card because it's going to make the pieces. That's gonna make the design a little bit more interesting later on. So I'm gonna say card dot move and pass in the piece card that move this piece. And the card itself knows how far to move it. Now, we don't have a move method yet, so that's unfortunate. And now they're also asking you here, let's pronounce that this player is taking its turn. And again, this is not really necessary for the thing to work. But we need to put some debug output here. Or else we won't know if our code is working, right? Yeah. So let's, uh, put the pair system that out. Print Lynn. Oops. Um, say, uh, player doesn't really matter exactly what your type here, but it should be, uh, is starting. It's turn something like that. So when we do run the code, something will print out on the screen saying, Yes, a player is actually moving. That's good. Okay, um, we need to define the move method in the card because we got two new methods that read right now. Drawling Move. Okay, uh, draw is going to be easy, but let's go on. Follow the, uh, instructions here, and we need to define the move method in the card. But we only have one square. There's no way to ruling move. So we're going to create the method where it's gonna have print one statement to, uh to show that that it was called right. So we'd also like to print the pieces position and the pieces number and its location. But since the peace needs as both of those information, let's delegate that to the peace. So in the card method, we're going to say ham playing a card with this value. And then I'm going to just tell the peace to print its location. Right? So let's go to the card. We're doing card up. Move public. Boyd, Move this piece well again. We can't really do any moving because there's only one square. It's pretty boring, but what's the playing that card. Okay, so, um, you say playing card, uh, value. And then we'll have this value. You could have said this dot value from 12 and then we're supposed to ask the peace to print its location once we're done moving eso eventually. In between these two statements, we will put the code in for moving when we have more than one square with the code in for moving. Otherwise, we say print your location, Mr Piece. Well, the piece wants to put its location is going to print its its number and the squares number . Right. So we're going to say Okay, so print location in the piece up. Sorry. That's not the peace class. This is a piece class public. Avoid prince location. Say, uh, peace. And then we wouldn't at its number is lips make a stringer is on square. And now I want the squares number, which the square is called position. And I want to say get number because I want I want to pull the number out of the square and print. It's looking. I can't just say position dot number because that number is private. So what it says now Is that okay? Now we have more problems, right? We're just getting it. Seems like we're getting more errors. Were not making any progress here, but now we want to add a get number method to this position. Object, which is a square, as eclipses telling me, and we see that from a pair. So let's go to the square and say get number. This is just a getter like we talked about in the slides, right? So we don't want people to be able to change the number of the square. That would be a disaster. But eso we have it private. Um, has it can only be set in the constructor, but we do want people to know what the number is. So it's not a harm to have a getter here, okay? And so now we saw this one red number that says the method draw is undefined for the type deck. So we forgot about that one. Let's go over here. And when someone draws a card from the deck now here we finally have a return value. When I call, draw on the deck of cards. I want a card sent back to me, right to draw a card. Now, of course, at the moment there's only one card. So we just turn their card? No, but boring. Okay, we cleared all of our errors down here. Notice if you're on the problems to have an eclipse that shows where suddenly they all the errors have gone away. We had some red errors, which were compiler errors, and we had some yellow ones saying, Hey, you've got some variables you define that. Don't actually do anything like that. Sure you did that, right? Yeah, we're fine. Okay. So now we should be able to run our game and something should happen. Something like this. And the way you do that is you find the main method, which is the sorry game, right? Sorry. Game class contains the main method, so you should be able to any clips? Right? Click on the sorry game. Get this big menu down here. It's run as Java application. All right. Click that it should run. And if we did it right, we see it. So peace one is on square one player blue is starting its turn. And like, this is not the top. I'm sorry. Okay. Player Blue start to turn playing a card of value three and Peace One ends up on square one , and then player Blue does another turn playing its card of value three and player one is on square one. So there's only one square. And there's only one cards that the values always three and the peace stays on square one. Okay, we'll fix that. But our little simulation is working now. This kind of output is a little bit confusing. We can put some blank lines in here, so let's say let's go back to the sorry game after the player takes a turn. Um, let's go ahead and put in a empty blank line so it's a little bit easy to see. No, if I went to a class, it doesn't have a main method like square. And I said, Run as let's see, the eclipse is like, What are you talking about? Maybe you can Maybe you can go to this menu and figure something out. But because the sorry game has a main method, when I say run as it gives me this option Java applications. Okay, I can run the main method. Right? Okay, so now there's a little Pinellas A list. A line empty line between each turn. Right, So that helps a little bit to see what's going on. And of course, you could print. You have the number. I hear the loop counter, I so you could print out starting turn number. Or I guess these aren't turned these rounds or something. Like you go around the board. Right. So around number one, each player takes a turn around number two. Each player takes a turn. You could print out that number as well. Here. You congenial your output to make it look like how you want. Okay, But that finishes the Chapter six on objects, classes, constructors methods, attributes. And we now have a working programme consisting of six different classes in an object during the program. So congratulations. We're really starting to get into it. 11. 07 Arrays: Welcome to Chapter seven a raise. This is where we deal with more than one instance at a time. So up till now, our game is kind of boring because we have only one square, one piece, one player. We won't have more than one. So let's take a look at one of the first solutions job offers for this, which is rays, which are basically groups of objects. How to create them, how to access them. So, for example, we've only had one instance of a particular type. For example, we only had one player. And now let's say we want more than one player so you could make your first attempt like this and say, Player one player to player three And you might be able to get away with that for players. But that might be a bit harder for something like the squares, cause there's 60 of them. And typing out square zero square, one square to up to square 60 might be, uh, kind of Ah, not a pleasant task. And also you might miss one and then, but it begs the question of what if there were 600 like, Are you really going to sit there and type out 600. There's got to be a better way. Enter the arrays, so an array is a different type of object, so it is an object as well. That basically holds a set of references to other objects. So what you see on the top here is an array of players. Looks like it has four slots, and it's holding references to four other player objects. Player one player to player, three player for in holding all the references inside one object. So see what that looks like, so the hallmark of a raise and java are the square brackets. So when you're declaring an array, as in the first line here you say player square bracket, square bracket. And that's red as a new array of players, right or a player array, however you want to stand, and then the name of that object is called players. So when you declare a raise, your always using the square brackets and then a raise air also objects just like players or cards or anything like that, and so you need to create them with the new operator. So here you see new player, but instead of the round of parental like you normally have. When you're creating an object, a raise, take the square brackets and within the score brackets, you need to put an imager, which says the size of the rain. So the size of the ray has to be known at the time when you create the array and its immutable, it can't be changed after that. This is, we'll find out later is one of the biggest drawbacks of a raisin in the next chapter will fix that problem as well. Now one of the most interesting properties that come with the Rays. Every array has a property cult length, which is a read only property that tells what it sizes. So if we're running this code that we have here and we say players equals new player for and then later on, we say print out players at length that's gonna print out for How do you access a raise? Well, so first line there's the standard way of creating an array. Now we have four slots for players in our ray that we've created, and now on the second Legacy, players of zero equals new player, so the number at this point within the square brackets. That's called the index of the Array. One thing to notice here is that, yes, the Rays are indexed to starting at zero. So for an array of length for, like this players array, the ballot index numbers go 0123 So it goes from zero to a length minus one. You may think that's unfortunate. I think that's unfortunate as well. This is part of job is lineage coming from the C language programming language and then see , there's lots of really good reasons why you raise should start at zero. But those reasons have disappeared in Java, but we're left with the legacy of zero offset away. So just something up to get used to, that that ship has sailed at this point. Eso no, I created a player and have added it to the rain. What if I want it back later so I can talk to that player? You can access the elements of the array in the same way that you assigned them. So here you see, on the third line, you see players of zero. We say Player P equals players a zero and now p points of the same object that was in players of zero. Now one of the other things you have in an array is the not every index value is allowed. Right? So this is a player array of size four. So 0123 are allowed. What happens if you say players of six equals new player? Well, what happens is this. This compiles just fine, but when you run it at runtime, this will throw an exception on Array index out of bounds exception. Now, we haven't really talked about exceptions yet, but this is job his way of signaling to you that something went wrong. The fact that Java checks the array indices at run time and make sure that you can't overstep the bounds that you set is actually a really good thing. These kind of ah ray overflow bugs were a huge source of the hacking attacks in programs that were written and C and C plus plus, where you can actually do players of six and it will run just fine. Basically, if you let the arrays the re index run over the length of the array, then you have some almost random access to the memory of the computer, and you can do a lot of damage. So when this when job became out and they said, We're gonna bound, check Ola raise at run time. And if you if you put a bad index in there, it's gonna throw an exception that was really heralded as a great thing. Okay, again, just to drive this point home. When you create an array, it doesn't create the elements, right? So when you say, uh, player array players equals new player of four, you get an array with four slots, but there are no players in it yet. It's built to accommodate players. You can put players in it, but there aren't any players yet. It's kind of like setting a table with four place settings. That's great, but there's no people there yet. You need the people to come sit down. Just putting the chairs there doesn't create people eso in the lower half. You see here is how you would create the players and fill up the array. You have your ended your I from 0 to 4 and this is very common syntax for loop I equals zero. I less than four I plus plus. And then you say, Player of I equals new players never created for new players and assigned them to the slots . +0123 Inside the array, this syntax for a raise can vary a little bit. The one on the top line is the one I've been showing you. I think that's kind of the most intuitive. But you can. When you declare an array, you can actually put the square brackets next to the variable name. I don't really like this one because it looks like the variables and injure, and you have to kind of look over here to see, like a weight. It's an image or a ray, so I don't really care for this. Another interesting thing you can do when you declaring a raise you can. If you know the values already, you can just write them in inside of curly braces. So new interest in this case you don't need to given index because Java will look at what's inside these curly braces and go OK, look, there's 123 so this will create an interim A of size three for you and pre fill it with the values to 34 5 And in fact, you can even go further than leave off the new hint. Here. It's an implied constructor call you say into numbers equals curly Brace to 34 5 that creates the same, uh, structure as this one above it. So you'll see these different kinds of sin taxes from time to time. You know, in general, programmers are gonna prefer the shortest, most tourists in tax. But one thing that we've kind of touched on hair and want to call out explicitly is that a raise can hold object types like players. You know, different classes that you have written, or they can hold primitive types like it's bites. Doubles, longs, those sorts of the primitive types that are built into the Java virtual machine. Okay, so that's pretty simple. Look at a raise, but our project is gonna be a little bit more complex. So the first thing we're gonna look at is upgrading our knowledge of squares. So right now we have one square, but we know that there are 60 of them. The squares, The number of scores never changes. The scores were always in the same order. They don't move around on this on the board or anything. So it's a pretty good candidate to use an array for, so we'll have to create 60 squares will make an array of of 60 will go through and fill them all in the loop. And the first square will call the starting square right. And we'll just start the players on that square. And now we should actually be able to move our pieces around the board. When we pull the card, we should be able to move. I had three slots. Um but how exactly did that work? Right. So we know that the peace knows its own location. That's a square. So it knows worth sitting. It draws a card that says three steps, and now we have to move three steps ahead. And if you remember, we gave the responsibility of moving the peace to the car because the car to have the number of squares to actually be moved, but the card doesn't know what square is. Three steps ahead. So how are we going to do that? There's lots of ways you you could solve this problem, but we're gonna up for one. That is kind of a very elegant use of of object orientation. So what we're gonna say is each square knows its neighboring square the next square. So, like square number one, it knows that its followed by square number two. And it has a reference to that following square. And now if I'm on square number one and I say, Hey, I need to move. Where do I go next? The square can tell you. Oh, here, here's score number two. And then when I'm on square number two, I can say, OK, now where? Square number three and it will take me along the, um take move me along the board like that. So we're gonna go to our lab now and turn squares into an array. This is a little bit more complex of a of a lesson than we've done before. Oh, are complex exercise. So be sure to read the directions that come with the lab. Fall that along and when you're ready, go ahead and pause the video recording right now and give the exercise of try. When you're done, you can start the video again and we'll do it all together, all right. I hope you're able to get through that exercise pretty well. Let's go take a look. So, first of all, let's look at the exercise instructions here, and it talks a little bit about the design challenge and how we're going to do it. And I hope you read that. Hope that all makes sense will kind of comment on it as we go through. Um, so we're gonna do the create squares thing and it says, First thing the square classes now gonna have this new field called next square of type square with the getter in a center. So let's go find the square class. Dismissed that So it's not distracting. All right, so we have a new attributes. Let me know how to do attributes. We've done this before. Private square, next square. Okay, so this may seem a little bit odd to you that a square has a attribute of also a square, but it's actually a very useful, object oriented paradigm. Get I really like to use this way of moving around the board because it really gets you to think about objects and how they relate to each other. Now they said. We want to get her in the centre being a lazy programmer. I'm going to use the clips to do that. And I'm going to say source code, and it says generate getters and centers and I just want to do the next square. So put those down there and boom. Now we got getting next. Course that next, where it didn't exactly put them where I hoped for me. I like to have the constructor at the top. I was going to the construction back up. That's that's where. Expect to find it. Okay, cool. Now, next thing is his. Go to the sorry game class. Change the field name square from a square to an array of squares, and then we're going to move the creation of the scores, because is a bit of a mess into a method called create squares. So it's do those two things. So instead of a square here, we're gonna have on every of squares. Remember, that means curly braces. Instead of calling it square, I'm gonna call it Where is, uh, that makes a little more sense. And we said we're going to do all this work in a method called private method called create squares. Okay, so, um, we're talking a little bit more later. What private methods are member avoid means that this method isn't going to return anything . It's going to do some work, but there's no return value coming back. Notice we have a compiler right now. We'll get back to that a little bit later, all right? In the actually, they ask you to fix that right away. So let's go replace the creation of the single square and instead call create squares. So take all the cell and say create squares. There we go the way, if you're new to eclipse again the way I did the that little auto complete was by a control space. Okay, so in the crate Squares method, we're going to create an array of 60 for each and next we're going to create a square and assign it to the next. And then we'll have to loop over again and set the next square property. So let's hold on. Let's not do too much at one time. So we're first we're gonna assign to the variable squares, which is you could say this dot squares, if you wanna use this for everything. New square array of size 16. Okay, now second step loop over from 0 to 59 add in the square. Teach one. So let's just put a note. Hair, lips, substantiate. Squares writes a 4.0 by less than nil. I could do this. Great. I plus plus. And then I'm gonna do this. However, we're getting into what we call magic numbers here. So this number 60 and this number 60 better be the same, or you're gonna end up with bugs or crashes in your program, right? So truly Brad programming Celtic Teoh duplicate numbers like this throughout your code. That's like, Well, these will have to be 60. Everybody needs to know that someday someone might enter this method and start messing with it and not realize that if they change, we're using 65 now. Sure, that's fine. They do this and they forget they don't see there's another 60 down here. They might not expect that. And now you have a big meeting, This nightmare. So there's a couple ways to solve this. We could create a variable here, attended your called number of squares and assign it to 60 or if we want to exercise our square. I'm sorry. Our race and tax little bit that we learned in the slides. Let's do this. Spares. Uh, like, remember, We know that once you've created squares, then it has the as a length property. This number 60. If I change this number, this number changes. Right? So this is a very safe way to do this. The variable length can't be changed in any of it. So we say squares. Now what index too will you sign? Well, the variable eyes taking on all the values from 0 to 59. So that's the next we won. And we say new square squares, Remember? I want to know their number because they like to print out. I'm on square 12 or something like that. The player. So we pass in the annexes Welker. Okay, Now the other thing squares all need is their next square. Now you might think and this was discussed in the in the instructions for the lab. Maybe we should add that to the constructor of the square and say square needs to be passed in its next square. But because the squares air in a loop. You can't do that. In other words, in order to pet like for square one the next Where is gonna be square to see it to create square to before you create square one or else you can't pass it in right? Eventually you get to the end of the to the lining, you say, Oh, square 60 or I square 59 the next square square zero. So I have to create score zero before I create square 59. And, Ellen, I'm in a loop. I can't do it. So we have to do it in two ways to loops here. So we stand to get the square. Now we're going to say, set to be next square property. So let's start looping in for equal zero. I looked less than, uh, what we're going to find when we get to the end. Hair squares, link clips. Okay, I forgot the I know there's something missing here. I'm sure you guys saw that I was having trouble picking it. All right. Now, can we do this all in one loop? Let's let's try this. We can start with this and we say, Okay, so I want. Let's start with square zero. Hi. Equals zero. Okay. And so will say, um, square, Let's call it the current square equals squares. Zero. So now we're using the ray ups. Sorry, my bed. Scores of I now raising the ray access notation The next square after square I It's full of next square. Put me call, I plus what? Okay. And so now we want to say And so, for example, when I equals zero, we have Kurt squares. Score zero. Next squares square one. And we want to say current squared. Outset next square to next square, You might say, huh? Problem solved. Do you see the problem here? All right. I is going to range from a value of 0 to 59. Right when I equals 59 will be pullout squares of 59 then we'll be looking for squares of 60. But there is no 60 here. Right? If you run this code, you'll get that dreaded array index out of bounds exception. And you can try it and see if if you believe it, see if that happens to you. But I'm assuring you well so we can actually go this for? We have to stop one earlier. All right, so I'm gonna put a minus one there. So now I is going to go from 0 to 58 right? And so, uh, that leaves square 59 without its next square. All right, so we're actually gonna have to handle that by hand. So say squares of now, we want to get number 59. If I type 59 inherits more magic numbers because it has to be one less than this. Right? So what? I instead, I'm gonna do squares that length minus one. Okay, now I can do this. Could net. So squares of 59 which is what that is. Expression of values to That's a square, so I can actually call methods directly on the square. I like appear. We took the squares out of the array and assigned them to to a local variable. We don't actually even need to do that. Let's see much this ascent next square and we know that the next where for square 59 is square zero. Right. So we say squares of zero. Okay, it's get those syntax highlighting way. All right. I hope that makes sense to you. This is a little bit of ah, you know, requires a little bit of thought here to follow this code. And I went through it pretty fast. But you may want to look at it if you If you still don't get it, you can add some debug statements. Remember, each square has a number associated with it, and you can get the squares number by saying, What is it called? Get, uh, take a look. Get number on the square. Okay. And then you can put some print statements here and say, uh, current square is equal to square of get number, right square that get number. But this will set up your squares for the proper operation of the game where each square knows about its next number. Now we still have one compile over here. See this little red guy here and it says, Okay, we need Member. The player also need that starting square. So for at the moment, let's take our squares and let's say score zero is the starts where for all the players right now, there's only one player. Next chapter will have multiple players, um, for our version of sorry, we can have them all start in the same square, or you can be a little more elaborate and start among different squares. It it doesn't really matter. All right now that's only half the work after all that. A little bit of mental gymnastics now we need to move the peace. So we finally get to move the peace around. Remember, we said we will. We already assigned that responsibility to the card. And again, that may seem a little bit counterintuitive right now, but as we move along in the project, you'll see that there's a reason for doing that. So first you need to get her and center for the location of the peace class. Now, did we not right one of those before? Let's take a look. We did not. So we do have a, uh, position. They called it here. Location looks like sometimes it's called locations. Sometimes position. But let's do that thing we did before and say, uh, source. Generate getters and centers and let's put it last. I like my getters and centers down at the bottom. Okay, there we go. So now we have a get position in the set position down the bottom. Good. So the card needs to know where that where the square is. So for the card, we do this by asking the pieces current location for the net for its of the current locations. Where for the next square. So let's see what that means. So here we are in the card. We're not doing anything right at the moment. So what we have to do to do this moving? Remember the way we're gonna do it to say square start, location equals piece that get position, maybe should call it start positions. That nomenclature is similar position. OK? And now, whatever the value of this card is, it's an integer we're gonna each time say something like this. We're gonna before people zero I less than this stock value plus plus. So again, we're just doing a loop. Like if if value is three, we go +123 times that, I will take on the value +012 We don't really care what the values are. And then we'll say, Let's see, Maybe we shouldn't. Maybe we should call this position time and to move one square. What we're gonna say is uh, the position equals position. Got getting X square, right? So I'm using the same variable here. Maybe that's a little bit confusing. And I can say, um well, I think it's just going to make it even Justus confusing if I do it more. But so we start with the square. That is the position that the position that the pieces on then we say, Give me your next square and we take that square and we assign it back to the position. Variable right. We do that multiple times, and then when we're done, we have to inform the piece. We haven't told the piece that he's got a new position, so that will do it all right again. This a little bit. We're getting a little bit more into the object orientation. We've got the single variable position and we fill that variable first with the current position of the peace. And then we go through this loop. But we say, OK, let me ask that square. Give me your next square and I use that. And I replaced the value of position with that. Next where and then do that again and I do that again so that steps me along the board three times. All right, let's check our problems. Council. No problems. So what that tells me is that if I try to run the game, let's see if this works. Okay, let's read it from the top player. Blue is starting his turn playing card of value. Three piece one is now on square number three. All right. Player Blue is starting his turn again. Remember, there's still just one player playing accorded value. Three. Remember there still, just one card has value three, and now it's on square six and then it's on square night, and then it's on square 12. Then, since where? 15. Right? We kept the game at five turns, but now you can see the pieces actually moving around the board. It's landing on different squares, all right, so I hope that all makes sense for you. Let's go and summarize what we have here, so we learned about a raise. In this chapter. A raise can hold multiple variables of the same type so it could be primitive values or object values. You could have an array of imagers or an array of squares, an array of players very useful. So if we want to look at our project again, let's go back to the sorry game here and look at. We have 60 squares, but we only we keep track of them with one variable here, right? It's just squares. He didn't get the help like Square zero square one square to square three, which would be a real nightmare. And there's a little bit of Ah kung fu involved here and setting up the square that mean simply filling the array was simple, right? This is like dead simple code here, setting the next square property, this idea that the squares know about each other. It's a little bit twist your mind a little bit hard to get your head wrapped around it, but it's actually pretty straightforward. We do them all. We take the treat the last square as a special case so we don't We don't stop the next one early, and then we treat the last square as a special case, but you raise a really useful now. The big problem with the Rays is that the size must be known and declared when you create the array and it can't be changed. So in the next chapter will look at another data structure that holds multiple values of ah , given type. And it solves a lot of the problems that we have with the raise, the inability to make them bigger and smaller at runtime. All right, we'll see you in the next chapter. 12. 08 Collections: All right, welcome to Chapter eight collections. Another way to do Bunches of instances. So a raise, our super convenient. But they do have some problems, right? First of all, this in taxes. A little bit awkward, like all those square brackets and curly braces and things bit weird. And the big one, of course, is that you need to know the size when you create the array and you can't change it once it's been created. So that's actually a really big problem. Uh, so Java has a framework called the collection Spring work, which solves these problems. There are lots of different types of collections in this chapter will look at the most common one, which is the list. So when you look at this and you look at the left hand side and you say I haven't array of four players and then the fifth player shows up, what do I do? Well, I can't add 1/5 player to a four player array. I'm gonna have to create a new one. Would it be nice if he arranges to that itself? Like when you tried to add 1/5 player, you'd see, like here on the right hand side. I would just like, maybe doubles its size and, you know, adds a player that player five to slot number five. And then I wouldn't have to worry. I want to deal with all this mess. Well, that's exactly what collections are. So collections. There's a whole collection framework in Java, and they fall into several different types. One is lists. Those are a type of collection which preserves the ordering. So remember how Honore you have the indices like 01234 and you can access the state squares in the array by their index, so less work very much the same way things were put in a certain order, and they keep their order. A set is a type of collection that doesn't have an order, but it has a different property and that you can't put duplicates in. So if you add, uh, you know to number twenties to it, it will throw the 2nd 1 out. And then there's a different type of collection called maps, which is a key value store in a little bit different beast than the list in the sense. But let's start with lists because that's probably the most common one. And basically you can think of a collection as as, ah, object that just wraps Honore and it manages it when it gets full. It creates a new one with a larger size and copies the data over into the new ARY. So here's how you use list. So first of all, let's say we want to create A instead of an array of players, we want to create a list of players. Okay, the syntax here gets a little bit confusing cause there's things we haven't talked about yet, but we use the type here list and then we have this angle bracket player. So that way you read. This is a list of players. These angle brackets denote what they call a generic interface, and we haven't talked about generics yet, so that will come up in a little bit later in the course. Um, and then you say New array list of player again. You can say this is ah, rainless that holds players. But wait, why is it list here? And a realist here isn't that odd? Well, this has to go with list is the interface. An array list is the concrete type. That probably doesn't make any sense to you yet, but we'll be talking about that just in a few chapters from now looking at interfaces and how this works. But this is the proper way to declare a list of players, so let's just do it this way and, well, look, we'll examine this syntax as we go through. So if you want to add a new player to a list, how do you do it? You? There's an ad method that you call and you create a new player. All right, you can. That will just add the player to the end of the list. And if you want to put the player in at a specific index like you do in an array, then you could say Use the set method and you see players that set. And in next Number two, here's a new player object to put in there. If you want to get a player at a certain index, you can say Get in them. Passing that imager index there, and it will return the player so the first player would be at index zero. Right. Second player will be it in next one. It's Sarah, so it's still a zero offset array paradigm zero Offset index. Just like a razor Now, normally, when you're using lists, you don't generally go through using the get method and passing in imagers like you do in an array. There's more elegant ways to deal with it. So let's say here we have a list of players and it's an array less than we've added. Some players, Um, and we want to go through now to each player in order and tell them to take their turn right. There's a syntax for that which looks like this for a player player in players. So the colon is red is in player. Take your turn. So this is kind of a short cut for this sort of four loops in text we've been using with the Rays. And again you define your local variable player player. So this player and this player of the same variable right, and that comes out of the list players and the colon basically tells the compiler. Okay, I want you to iterate through this list of players, go from zero to end of the list and give them to me one of the time passed them into this loop, right? One thing that's not called out here, that's actually interesting to note in Java. Once you've said this is a list of player, you don't need to put the name player inside the the angle brackets. When you in Stan, she ate the array list. Okay, you can if you want, but that's generally People don't do that because it's just a lot of typing, all right, so you could do it the old way. And that is like, Okay, uh, it a rate for my equal zero to the size of the player. So on a list of items, the method to get the size of the list is called Size versus Honore, where it's called length. So that's a little bit unfortunate that Java chose different words to get the length of the different types of collection sizes. But that's the way it is, so you could write a for loop where I goes from zero to size, and then you could get the players that index I and tell him to take a turn like this. But I think you see that this syntax here it's a little bit more elegant, less wordy. Let's step to type and keep track up. Then this sort of thing. We have a full blown for loop with the three clauses, etcetera. There's other ways to do it. Orations to that. You might come across. We won't go over them here, But there is generators and way back in the day in admiration from Java. One data. Those are very old school. You generally won't see that unless you're looking at really old code. Okay, so, uh, list is a class, and people have wrote lots of methods, just like our classes have lots of useful methods. So does list. And we've seen the methods like get set and add already and also the method size to get the size of the list beyond. Beside those, there's one, for example, at all. So it's I have a different list, and I want to add everything on the list to this list. I could just pass the whole thing in, and it will at all of them clearing the list, empties it out and gets rid of everything, turns back to an empty list. You can ask whether a list contains a certain objects A supposed you have, you know, a list of players, and I and I have a certain player. I have the blue player over here, and I say, Wait, is the blue player in this list? Let me ask. So contains is a method that lets you ask. You can ask the array or I'm sorry. You can ask the list of its empty. You can remove an object from the list, and you can also sort them using something called a comparator that will look at a little bit later. Okay, now, one disadvantage over a raise for this is that they can't hold president, so you can't do a list of int or double or floats or something like that. However, there is a type called Integer Capital I integer, which is a class rather than a primitive. Those air, called the Job, is rapper classes, and there's a whole thing to talk about those We'll talk about those in a later chapter as well. But if you really need primitives, for example, like you're doing numerical computations, you'll probably want to use a raise because the rapper classes, like integer, are a little bit slower than its. And if you're doing a numerical calculation, where your summing up you know, 10 million in its You probably don't want to use indigenous because that will be a lot slower for that many accesses, then just end. So in those cases, like if you're doing scientific or numerical calculations, you're probably still going to use the race. But for the standard kind of business programming, or like our game simulation here, you definitely want to use lists. Okay, so that's enough to get started. We still have to places where we have one item where there's really in real life more than one. The players in the cards, All right, so we're going to change our gay our simulation game, to have a list of players and have the deck to have a list of cards. Now there's still one of the place that's left is that is the pieces, like a player could have more than one piece. For now, we're just gonna were okay with the player just having one piece. We can still move him around the board. They can still compete with each other. It will be still be interesting game. So once again. Uh, you can pause the video here, go to your project, followed the instructions, because again, this is it somewhat involved. Exercise compared to the earlier ones in the class. And I'll just you can pause the video here. And when you're done, come back and then we'll work on this together. All right. Well, welcome back. Let's see how we can do these list exercises. All right, So, um, we need to places. Let's look at our instructions. First, we get too far off the instructions, go to the sorry game. Remove the player attribute in at a list of players. Okay, So let's get back to our sorry game here. I hope so. I was in star game, huh? All right. It says we're not going to have a player. We're gonna have a listed player, so they list. Then we're gonna call it players. All right? Now, one of things you'll see right away, his job is claiming he I don't know what lists are. All right. This is the first time we were using a class from the job a library and we have to dio perform a little worker that's called importing the class And what that means is we have to tell Java, which, because there's many classes out there called List that we have to tell the compiler which one we're talking about. Now there's lots of ways to do this After list, you can put your cursor there and hit control space, and it will pop up a little dialects thing. Which list do you want? Uh, another way you can do it is through this source menu, right, clicking source. And there's something here called organized imports, which is controlled shift oh, control capital O in windows. And when you do that, it actually does the same thing. It's OK. Which list do you want? It brings up this chooser and what we want is java dot You till that list. Okay, so these things like job that you till java that a deputy calm that sun dot tools not jump asi that you tell these air water called packages will be talking about packages again in a later class. But these three list classes are all very, very different from each other. So you want to make sure you get job that you till that list, OK, so make sure that selected you have finished and now the red line goes away. Now what happened? Look at the top of your code. There's now an import statement. This is import Java Util list. We'll talk more about this when we talk about packages. But this is just telling the compiler when I say list, which listed my talking about I'm talking about Java util list. All right, so with that out of the way now we have a problem here and it says, Uh, there is no such thing as player anymore. So its players right? But players is not equal to a new player, right? And as it says, it's going to be an array list, right? So let's ah, what's going to keep this? Because I will use that later, but I'll say new a realist now. Same problem. Ray list is red because Java doesn't know what's array less. I don't know what you're talking about now. I'm gonna do the other method control space and it says Ray List. Yet that's the one I want. And it fills it out like that, and it puts in the the type player again. The fact that player is already here. Joppa understands. This is a list of their A list of players, so you can actually delete this and it doesn't turn red. Job is happy with that, right? So it's like, OK, you can do it either way. Generally, this is called Diamond Syntax. When you do it like this, that's the preferred way. Just because again, there's less clutter in your code like you don't need to declare player twice. And it's a bit We talked about magic numbers in the previous chapter. It's a bit of a magic type declaration like this player, and he's equal this one in here. Or if you, if you type something different if you type in Square is gonna break. Said it doesn't like that. All right, now it says, Um, okay, we talk about doing that. Let's create two players blue in green. They can both start on the first square. Okay, great. So remember how we do this with players dot Add So we can say this, not players. You gotta spell it right. Add some new player. Okay, well, here is a new player. Let's take Purcell. We don't need that anymore. Cut that in here. So I'm creating a new player, hair in place and passing in directly to the ad method So you could have certainly said Player P equals new player and then say players that Ad P, that's totally fine. But you don't really need it. You can just do it like this. It is a bit of a shortcut again. So showing you some shortcuts and we said one blue and one green. Okay, now we have a blue player in the Green Player. Now we both left, and we let them both start on square zero. That's fine. If you want your green player to start on some other square like square 15 or whatever, you know, fourth of the way around or something, you can change it. That's fine. Not gonna cause any problems on that note in the rial Sorry game. If one player lens in the same square is the other one, you knock that player often, send them back to their home. In our simulation, we're not going to get that sophisticated. So the fact that the players start in the same score doesn't really mean anything. All right? Now it notes the compiler and instructions. Both note that the plane method is broken. All right, because we used to go around five times until the player take your turn. Take your turn, take your turn five times. But now we have multiple players. So in each turn, we need to have the players each player take their turns, right? So we need to do that thing we talked about Iterating over the list of players. Remember that four loop syntax from the slides. So for player P in players, we're gonna take its turn like this. It's evident that so it looks a little bit nicer. Okay, so this is Ah, remember when we play, we do five. What you call these rounds. Um, and I need to call this so notice that we've got a compile over here. This is I don't know. A player is You called it P? Yeah, that was my mistake. That should be player. Sorry about that. Okay, Now it's happier This letter, I this is this is like the number of rounds that were playing right. So you could call this round instead of I If you wanted to. On then we loop over the players. Remember the players air in a list. So the water is preserved and blue players going to go first and then green player. Right? And if you wanted to, you could put another help up here, uh, starting ground. And then hi. Right. So then when our output on the screen each time we started me round, it would say, Hey, we're starting ground zero. In fact, it's going to go 20035 or 034 Given are for lead. Okay, that takes care of the sorry game where we now have upgraded our game from one player to two. And, of course, we could do as many players as we want here. We could add 1/3 player, player, red player, yellow player, white player, black and at as many as we want Member lists can hold as many players as you care to add right. They'll stay in the same order that you declare them. So you call. Add the 1st 1 at the second at the 3rd 1 Uh, they will stay in the order that you've added them to the to the main list. All right. One more thing to do to get this thing working is a really deck of cards, and this one gets a little more complicated as well. A zit talked about up above in the requirements part of the section. We really have to piles of cards and you think about it. When you're playing a card game, you have the draw pile and the discard pile. You pick a card above the drop, I'll you play it, and then you throw it on the discard pile. And when the draw pile gets empty, things shuffled to discard. Pile and those cards go back in, become the draw pile, right? So let's try to simulate that a little bit in our code. So we have, uh, the deck class. Now let's take a look at what deck looks like it. The minute it's very boring. It has a card, and when you draw it returns the card. All right, let's do it a little bit better. We're gonna have to lists of cards. So let's the card called that draw pile in a private list of cards called the discard. All right, and I'm gonna there. I did my control shift. No. Two. Important. The list class. Great and let's see what they say here in the constructor create the two array lists. All right, so no more of this nonsense. We're gonna say draw pile equals new ready list and discard Pile equals new realist. All right, notice that I didn't use this dot You could use the stott. Also noticed that job. Our eclipse colors the variable names so you can see that this is blue and this is blue. And that sort of to draw your attention like, hey, this draw pile in this draw pile. Same thing, right? That's what you're referring to. You could create a local variable called Draw pile and that would override that, and it be colored differently. But let's not get too far off, okay? We need to create some cards. Let's make values from 1 to 12 and like to make four of each. So we're gonna need two loops here, one where the value goes from 1 to 12 and the other one that that just has four counts to create for this. All right. And then it says after you created card added to the draw pile. So let's do this. We'll just there create the cards. You could put this in a separate method like we did for creating the squares, but it's not quite as complicated. So we want to create values from 1 to 12. So let's call this variable value instead of I. And let's say it starts at one and we can say less than or equal to 12. Right? And so now the value the value of value will range from 1 to 12. And we said, For each value of each card, we're gonna create four. So for this one, we just need a generic for Loop zero I less than four by because Plus, for me, it was a card. Hard new clips, new card of value right out of I write because I want to make four cards that value 14 card that value to for credit value. Three all the way up through the deck. Okay, so and then it said at each card to the drop. I'll so we're gonna say Draw, pile looks. You all right? I have the card. Great. No, it's talking about Let's make the game a little bit more interesting here, saying, Well, we could leave it like this but the cards role in order like we have four ones and then four twos and four threes and then four fours and still going to be very boring. The game was very predictable. So let's shuffle the cards now. We're gonna need some random ization here where we want to make these things randomized. Um, that's a little bit beyond what we want to do. It turns out there is a class in Java called collections collections. So turns red because we have not imported it. I'm going to control space. And it's his job that you till that collections and it has a method called Shuffle, where it shuffles a list. So I'm gonna shuffle the drop ill, all right. It's not something we talked about in the slide them just drawing your attention to it. Here. It's a very useful thing. We'll talk about the collections class in the later lesson. It's got some useful methods, like Shuffle, for example. Okay, so now we need to update the draw pile because the dropout was just returning the loan car . There is no card anymore, so let's do it the way that we do it kind of in real life, right? So, uh, let's grab this. And we say, um, we need a card. Flips card card equals drop. I'll get zero, right. It's going to get the first card off the draw pile, and that removes it from the drop ill. Now, we're gonna want to return that card to the person who's calling the draw method right to the caller eso we do want to say return card, but remember what happens in the real world. You take the card off of the draw pile, and then you put it on the discard pile, right? So we don't lose it, because right now we've removed it from the drop I'll list. And if we don't do something, whether we're gonna lose track of it, right, so we say the discard pile and card. Now the ordering here, if you're thinking about real life, you say, Well, I I draw the card and then I play it. And when I'm done, I discard it when you can't do it in that order in Java. Because the return statement always has to be the last statement of the method, right? You can't You can't draw the card return it and then discarded later on. Like that. Syntax doesn't make sense in jobless, so you have to put the return statement at the end. All right? Now, I wonder if anybody sees a problem with this, right? If we play long enough, if we take up enough players and go enough rounds, the draw pile is going to become empty, right? And when we get here, what's gonna happen? When we say drop, I'll get zero. And if there's no cards in the draw pile, we're going to get one of those index out of bounds. Exceptions, right? Sort of very similar to what we saw on the on the A Ray chapter, and it's gonna crash our poor little program. So let's think about what we want to do. Yeah, the draw pile is empty. What should we do? This little space? There's some room. Here. Make this so you can see a little bit more of what I'm doing. Okay, well, what do you do in real life? If the draw piles empty, will you grab the discard pile? You shuffle it and you make that become the drop ill. So let's call that operation reshuffle because I'm going to reshuffle the cards. Well, what is reshuffle? It's going to be a little helper method we're gonna add here now. I could just go type this in, but let me show you some more Eclipse live here. It gives me it, underlines the rant and says, Hey, there is no method. Cold reshuffle. What are you talking about? And then it gives you some quick fixes, One of which is maybe you want to create that method. It's like, Well, yes, In fact, I do. Look at that. So now I didn't have to type private void reshuffle it did it. And it left this helpful little hand here saying, Hey, don't forget you need to put some code here. I just auto generated method for you, but there's nothing there. Okay, we get it. All right. So what I want to do here is I want to take all the cards from the drop ill and then back. I'm sorry. From the discard pile and then back to the draw pile. Then shuffle them. Shuffle it again. Right. So remember them The methods that we saw it, we can say draw, plow and all from the discard pile so that takes all the cards that air in the discard pile moves them into the draw pile. Now here's something where objects in the computer differ from objects in real life. In real life, a card is either an Empire Lee or the other. It can't be in both piles simultaneously. But in this in the computer memory, it can like the draw pile and the discard pile can both have a reference to the same card. And that's the problem we have right now is the cards are all in both piles at this moment . Well, we don't want that. We're trying Teoh empty the discard pile and put everything in the draw pile so we can say Discard pile dot clear right? We saw that method on the slides. All right. Now the discard pile is empty again, and we're all good. The last problem we have is that the cards are still in the same order that they were the first time through the deck, and it might be fun to change things up a little. So let's use our shuffle method again, right? Drop ill. Okay, so every time we're drawing card first we check is a drop. I'll empty from the previous turn. If it is, then let's do a reshuffle, which moves all the cards in the discard pile back into the draw pile and then shuffles it . So we get a different order so it makes a little more interesting. And then we draw the card off the top of the deck, added to the discard pile of them. Returned that card back to the person who called. All right And details of that, of course, were in your notes here, so you could, uh, take a look at it and follow it along fairly closely. But I think we've got everything. Let's take check our problems Tab. No compiler issues. So let's try running our sorry game and see what happens. Move what was fast. All right, let's take a look. Starting round zero player Blue is starting its turn. It got a value 11 soap. Eight player moves his piece from square zero to square 11. Player Green also got an 11. Now there's something wrong here. Everybody's gotten 11. Let's see. What did we do wrong? Um, has shuffled pile. Okay, let's see who's drawing the card that piece or the player, I think. And card moved Piece. Mm. Uh huh. I see the problem here. Maybe you caught it already. When we draw a card I wrote here, draw piled up. Get zero. That gets the card at zero at first position, but it doesn't actually remove it from the deck. Right? The method I'm looking for is removed. Okay. Sorry about that. Let's run our little thing again. And now it's a little bit more interesting. Starting rounds here, Player blue plays the card of value. 10 ends up on square 10. Player green gets accorded value. Three ends up on square three. Starting round one player blue gets card of value one. And now player Green gets a card of value six and goes on down lines. And now there's a little bit of competition here. And at the end, we end up with player green trouncing player Blue 43 to 27. So, player ah, blue had some bad luck here with the two and a six and ah, one and the three of the three of the green. Uh, but anyway, player Green won that round, so let's hop back to our slideshow here. This is summarised collections that we saw solved the problem of the fixed size problem of a rate. Remember, when you create an array, you have to say that how many items that's going to have, But when we created a list, we don't have to say that we just keep adding objects to the list until we're feel like we're done right. Also, the list have lots of other useful meth methods and, like size and at all, and clear and remove set methods that a lot of them didn't exist for. A raise lists of the most common version of Java collections and in this chair. But we saw adding removing iterating over objects in a list. All right, we'll see you in the next chapter. 13. 09 PolymorphismAndInterfaces: Okay, welcome to Chapter nine, where we're gonna talk about polymorphism and interfaces how to deal with different types of things. Okay. So often what we're doing. Software. We have different types of a single concept, like we have different types of animals, different types of vehicles, different types of players or people or employees. And sometimes it's a bit of a trick to keep track of all the variations. So in object oriented languages, there is a facility called polymorphism, which helps us deal with this. And then job interfaces are a key way to implement polymorphic techniques. Let's go through and see what all that means. So it is really coming have multiple types of things in the software program for the examples in the slides here, we're gonna talk about, Ah, some kind of software that maintains a list of people, a list of users or members or something, and we like to contact them, and they each have a set of contact methods. So a contact method could be contact the email via text Facebook message, Twitter, instagram, whatever all the different contact methods are you want to add. And how do you keep track of all that like when you want to send someone a message, How do you know? How do you How do you know how to do it? Based on the contact method? Well, the straightforward way is to kind of make a bunch of, if else statements. So here there's a method called Send a Message of this contact method and you say, Well, if it's an email, if the contact type or contact method is email, then you know, do some email stuff else. If it's text, then contact to text or else if it's Facebook, then do that. And you can just sort of enumerates all the different types of contact methods. And you know that certainly works. Um, however, if you start to need to do other operations, let's say you need to authenticate as well. Well, the way you have indicate with the email server or the SMS server or the Facebook sever those air different as well. So now you need another. If else block of things for the authenticate method, you can see where this is going to lead. It's gonna end up creeping all over your code. So if else blocks which blocks these air fine, except they have a lot of problems. They tend to replicate themselves all through your code, like we saw in the previous slide, and even worse than that, it creates multiple points of maintenance. So every time you add or remove a type of contact method, you have to remember where all of those if else blocks are all those switch blocks and make sure you change them, all right. And if you miss one, you can have a real disaster on your hands. They're also ugly and hard to read, like they tend to get really long and really detailed and really gross. And so you have one method that has all the details about sending a message to Facebook and the details about sending a message to SMS server and the details about sending a message to UNE email server. And that's a lot of detail to slam into one little method, right? And once you have all that there, there's gonna be some similarities between some of the cases. And so it's really hard to resist the temptation to abstract some of that code out and put it at the top. And now all the different cases. Air couple together. And so, if you if you're editing that code for one case, you end up potentially breaking a bunch of other cases. And in any went, uh, if you have good Q A practices, if you modify it, that method that has blocks for all the different contact types and you really better test all of them because you may have introduced a bug into that method. Who knows what happened in there? And so your Cue 18 will probably want to test everything. And that's a role starts to be rolled burden when there's a lot of different types. So let's find a better way in object oriented languages. We had this idea called polymorphism, which is built to solve this problem. So we followed this principle that on object is like a manager. They liked to delegate. They don't like to do the work themselves. So that method that we saw on the first set of methods that had all that detail like that's not the right way to do it. You wanna give the test to somebody else, so it's like we get these contact method objects. Can't we just tell them to send the message. They know what type they are right, like the email contact method object. It knows it's for email. It's in its name. Why doesn't do the email? Why do I have to do it? And so what we want is for all the different contact method objects to react differently when we called the sent message method depending on their type, you know your Facebook or Twitter or SMS, they do different things that's called polymorphism. The word means many shapes, and so it means like when you send the same message command, the different objects will react differently. There are many different shapes quote unquote to their reaction, right? So how does it looking code? Let's get onto it here. So, first of all, uh, what we want to try to get to with Polymorphism is in that big, ugly method we had a minute ago send message to passing in a contact method object. Now we just want to send a polymorphic message. We just want to say, Hey, contact objects, send your message and the contact object will do the right thing based on its type. And we as the calling code here don't need to know what type of contact method it is. That's the key point. That's what reduces the complexity in this method. And as a bonus, our method has collapsed to one line of code. So it's kind of hard. Teoh. Screw that up, right? There's no predicting there's not many bugs in this method. All right, in order for this to work, let's say we have a class that's called email contact method and then have another class. It's called text contact method, and then we'll have, you know, Facebook and Twitter it center. We have a whole host of these contact method objects. In order for this good to work, they all need to have a meth method called send message, right? And so each message each method has to be named exactly public void send message, and if they don't have the same method name, it's gonna break right. So let's say, a year from now you hire a new programmer and you tell them to add Twitter. Are you sure that they know that it has to be named public voids and messages? They might not even know that, and they might spell it wrong or maybe return different value or something like that, or give it a parameter and then it's not gonna work. It's gonna break the message. So how do you keep these method signatures and sink? Well, this is where interfaces come in, so in job. But we have this thing called interfaces, which looks like a class. Get my cursor here. So it's like instead of public class contact methods, is public interface contact method All right, so it's a different type of beast similar to a class, but in a interface, you can define method signatures without a nim, Plantation sees a public void send message and then a cynical right. It ends there. There's no curly brace. There's no lines of code there. And this is what in Java and general, this is called an abstract method. It's like I'm saying there's a method called send message, but I'm not telling you what it does. And then the individual classes like email contact, method, text, contact method, they're going to quote unquote implement this interface and have a method with this method signature. So let's see what that looks like. All right, so here's email contact Method Class and text contact Method class. We got this new keyword here called Implements so any class can implement on interface. And when you do that, it means you have to have the method that the interface declares. Or else the compiler will flag that as a za warning. There's another PCC here, which is this funny looking at override. Okay, what? That so in job. But things that begin with at are called annotations, and it's kind of like metadata. Generally, it's a an instruction to the compiler, although now not always, but no. At this point it is, and we'll talk about annotations later. But basically what this says is that hey, I expect this method to appear in this interface, right? So it's saying I'm overriding that that, uh, that method, that's it that appears in the interface. And if you spell it wrong here, or you or that method this method doesn't exist in the interface. Then the compiler also well notify you. All right, so let's look at it again. So the compilers gonna help you keep these methods signatures in sync As soon as you implement on interface. If you don't put the method in the body here, you're going to get a compiler error. It's going to say, Hey, you implement contact method, but you don't have to send message method in your class like that's an error and the same thing for the override. Ah, annotation there. So even if you had at another location in the text contact method, even if you had send message method defined if you had another one here and you say at override send text message, well, that does not exist up here in the contact method. So this is gonna also generate the compiler warning. So between implementing the interfaces and marking the methods with override at override, it helps you compiler will let you know if your method signatures get out of sync. If there's something wrong with your class definitions, you'll get a compiler warning or error, and it will prevent you from going further. All right. A couple things about interfaces you can't in stand shaped them, so you can't say contact method equals new contact method. Right interfaces can't be in Stan sheeted. Now there's an old Chuck Norris joke about how tough is Chuck Norris. Will Chuck Norris, Canon Stan? She ate interfaces. But no, we can't because what would you do if you had this object, this contact method object and you called Send message on it. There's no there's no Method body here, right? It's just a semi colon, so the thing wouldn't know what to do. So it's sense it's nonsensical to create an instance of an interface. So what do we do? Well, we create those concrete types, so here's the standard way of doing it. You have contact method. Method number one is new email contact method contact method with two equals new text contact method. So here we say that the type is contact method and the class is this specific one. So the type refers to what type your telling the compiler that the variable is so this variable Method one is a type of contact method method to is a type of contact method. But the class that you're in Stan sheeting, these air classes here, new email contact method, new text contact method so you're types can be interfaces, war classes and from now for previous to this, we've always seen classes like Player player equals new player, right? So it was the same the same type as the class that when Stan shaded. But, um, variable types can be classes or interfaces. And But when you and Stan Shade, an object has to be a class you can't stand, she ate interfaces. Now the reason this syntax work is because une male contact method is, ah, contact method, right? So when you say contact method Method one is new. Email contact method Well in email contact method is a contact method, so it's not a lie, right, And the reason this helps you to do it by making to keep your coat clean by making the contact method into an interface type is that it lets you to write very generic code. So here's some code down below, which is written just in terms of contact method. So there's a list of contact methods, and they could be email contact methods, text contact methods, Facebook contact methods that could be anything but you get them just as a list of contact methods. So again, the type of the list is contact method. Now you can just rip through them and say, send message. So this code is very generic, very simple hard to put bugs in because you're not dealing with all the variations between text and email and Facebook and Twitter. You're just looping through these contact methods, and all you know about them is that they have a method cults and message. We just fire away. Treating them all the same is the big advantage of having polymorphic types and polymorphic method signature so that you don't have to know anything about the details. You just know they have this method signature, and you call it all right. So some advice here remember the email contact method is a contact method. Or maybe more precisely, you say is a type of contact method, and the contact method is in the more generic type in the email. Contact method, obviously, is more specific, right, so you always want to try to keep your code is generic as possible. That more generic your code is the fewer bugs it's gonna have, the fewer reasons you'll have to change it. Um, if everything's Britain in terms of contact methods and you add or delete the email contact method, you have fewer changes to make. Then, if you had that turned the type email contact method sprinkled everywhere. Right. So whenever you create objects that you're going to be using polymorphic Lee make the variable type the interface type like this, like contact method, and then instead shape the actual concrete subclass like this with the concrete class like this. All right, just real quickly. In case you're interested in the UML, they call this generalization specialization, and it's denoted like this. Um, you have this shape of the air ahead actually means something in, um El So this closed triangular our head means generalization specialization, or people call it Jen spec because it's too many syllables on the dash line means interface implementation. The solid line would mean class inheritance, and we'll talk about that in the next chapter. We haven't talked about that yet, and the arrow always points from the, uh, more specific class to the more generic class. All right, that funny looking thing inside the angle brackets at the top. That's called a stereotype. And that's another UML way of saying, Hey, this thing is an interface, okay? And not in the UML, but in terms of terminology, you'll hear these terms subtype and super tight. In fact, It's kind of hard to talk about interfaces without using these terms. But the more specific thing is called the Subtype, and the more generic thing is the super type, where the more specials more specialized concept is the subtype in the more generic Generalized one is the super type, Uh, and when we get to inheritance in the next chapter, you'll hear a super class. And subclass when you actually have interfaces is not exactly proper to, say super class, but the people still do. You'll also hear of, ah, parent class or parent type and child. You also hear ancestor and descendant. So we use this thing's kind of as like almost like a family tree type of terminology. And remember, back to the UML, the arrows always point in the direction of dependency, So the contact meant that interface. Remember, it doesn't know anything about email contact method, but in the email Contact Method Class, it says, implements contact method so it knows about contact method. If someone deletes this file, this one will fail to compile right, because it won't know what contact method is. All right. More controversy. There's a naming controversy with interfaces sometimes uh, it's not clear what you want to name these things, because let's say you have a person class, and for some reason you need to make an interface for the person class. What do you call it? You've already used the term person. So how do we can have two things named person? Right? So there is one way of doing it where people named the interface. I person. I think this came out of Microsoft, but I standing for interface, of course. And then the actual class is called person. Some people hate this with a vengeance, and what they'd rather say is the interface should be named person. And then the class can be called like person Simple, which stands for person implementation, right? Doesn't really matter. It's probably good to pick one of these styles if if it comes out this way and follow it. But there's make you where you'll see these two naming conventions quite a bit. Okay, let's get onto our project. Let's see this step in action so we're gonna add a new requirement to the project. We're gonna have two different types of cards. Some cards, move the player forward and some move the player backwards Now, just by the way, I stated that that should start screaming to you polymorphism, right? When you hear I say there's two types of cards. Remember, the very first slide of the chapter was, Sometimes we have multiple types of something. So here we have two types of forward moving card and backwards moving card, and they have different behaviors. One moves the Pele or forward Mom moves the player backwards. Okay, this is screaming for an interface and for polymorphism, right? Remember in the player when when we say Take your turn, he draws a deck from the card and it says, Head card moved this piece. All right. I don't want to change this code. I want this to stay very generic like this. This is a member. Look at this. The player doesn't know what type of card he's got doesnt know if its forward or backwards , right? The card knows, and he tells the card moved the peace and because there's different types of cards, they'll do the right thing, right? So let's move on to take a look at that. First of all, how are we going to move backwards. This sounds like a nightmare. Right? So remember how we did moving forwards? We would ask the square giving your next square, and then that would be one step forward. And we do that. Like if the card had a number five, we do that five times. Next. Next, next, next, next, And then we'd be five scores ahead. So we're just gonna follow that paradigm to go backwards? We're gonna ask for the previous square. Um, so that's actually pretty easy to set up. Because if square number two here is the next square for square number one, that means that square number one is the previous square for square number two, Right? No exceptions to that rule, it always works this way. It's like for those of you who know some data structures, it's a doubly, you know, a doubly linked list. Right? So how are we gonna change the square class? What? We already had the next square attributes. We're gonna add previous square as a new attributes. And then when you set the next square here, you have square one and square toot, like right next to each other in the same method. So when we say the next square equals next. We can just say if this square is the next square for me, then I'm the previous square for him. So I'm going to set it in like this, right? If you think about this coding, you look at it and can diagram it out or whatever you want to do. You can commit yourself that this works fine. Okay, so we're going to go into the project. We're gonna create a card interface, Two types of cards. Uh, this is a little bit involved again. So I encourage you to follow the instructions or if you have a lot more confidence, you can just crank right into it. What we'll do now again, as usual, is you composite video. And then when you're done with your project, come back and I'll walk through the project with you. Now, even if you don't like to follow along with me on the project, maybe you got it toe working. You don't care to hear my explanation. That's fine. But after we do that, there's there's a few more slides left in this chapter. Some more advanced topics about interfaces. Don't forget to view those slides. Okay, so make sure you come back after the review of the project. So go ahead and pause now and then we'll come back together when you're done, and we'll talk about that project. All right, Well, welcome back. Let's go do the project. So let's call up our little we can make that wee bit bigger. Here's the instructions for this chapter using interfaces and it talks about we're gonna have two types of cards. We're gonna have a forward card in reverse card. Um, it also makes the the excuse upfront. We're gonna take the card from forward card and just copy it into reverse card and then modify. That's not good software engineering. But there's not much we can do about it until next chapter when we learn a new syntax in Java that will help us to get rid of all the duplicated code. Okay, so let's try it. Let's do it. Reverse quarter. So first we're gonna do that thing we talked about in the slides and add the previous square. Right? So it says that a previous square property and then put that into the extra code in the center. So we have next square. Private square, I guess. Square. Right. And when we set the next square, if that square is my next word than I am that squares previous square. Now we're going to need getters and centers before we do this. Right? Almost forgot that. So, uh, second, let me do it. I have to right click to say source. General Motors and centers for previous square put at the end of the file. Okay, cool. Right now, I could go back to where I was, and I was going to say, If that next score is my next square, then I'm his previous square. So I say, next square, that's the previous to me. And I remember, how do I refer to myself? Is this right? So these kind of methods were your You know, one square talking to another is a little bit sometimes confusing. Um, but if you think about if you work with that, you'll convince yourself that this is the correct Waiting to set this up. All right, let's go into the cart. So we want to take all the code we have in the car to class now and now that becomes forward card So the way we're going to do this is with the i d Easily factoring. Now, this is a little bit of there's other ways to get this work done. I wanted to show you the re factoring tool. It actually creates a little bit of cleanup for us as we'll see as we go through the project. Maybe you saw that already, but, uh, it's just one way to do it. So it's a very factor Rename card to be Ford car. I mean, you could call it forward moving card or something like that. That's fine. Whatever you wanna call it. Okay, so now we have forward card and noticed it changed the name of the class. It also changed. Um, the name of the file on the file system, if you looked like this is now forward card dot Java, right? Otherwise remember, it doesn't work if you don't have the same name. And any place that card appeared in the code has also been changed to forward cards. Did like a global search. And replace basically Okay, Now we need to reverse card. Well, now we do the cheating, right, So I can grab this forward card I can control. See? To copy. And I can control be to paste it. I'm going to say reverse car. Okay, that's bad programming that we're gonna do it this chapter and the next chapter, I promise you will fix that. Okay, So reverse car. Oops. Get it? Get every go. And it says what you want to do in verse card is instead of moving forward by using next square, you want to move backwards by using previous square. So really, everything else here can stay the same for now. Except we're changing this method to groups previous. Right now, this card moves the pieces backwards on the board. Kind of interesting. All right. Um, no, I need to update the deck because right now, the deck is only creating forward cards. We can't add any reverse cards to it. So they look at the deck, are re factoring, had some fallout here. So if I look at the list of cards at the to list here, it says forward card, discard pile forward card, drop ill. So I can't add any reverse cards because this is a concrete type. I wanna have a generic type here, so I can add both types of cards to my lists. Right. So here we come, creating its card interface. Alright, school this down a little. All right, we're gonna create an interface card, and then we're gonna have both of our forward and reverse card implement the interface again. There's other ways to do this, but, um, let's just go with this path will say new interface, All right? And see that it says public interface card now. Okay, great. And then we want to get our implement statements in implements card and first card moments . Now, notice. At the moment, that hasn't really gained this much, because remember, we said interfaces are away to declare method signatures and keep everything in sync. There's no method signature in here. It's just card. Okay, we're gonna fix that, of course. But what we can do now in the deck is we can go and we can make these back to very generic things. All right, So he changes back now, these air broken because, actually, um, we haven't talked about generics yet, but you don't really need this. Let's just take those out and that we won't have this problem ever. again as of Java seven, I believe you don't need to put the type in twice. If this is a list of cards than this is an array list of cards. It knows that from this one. But we haven't really spoken of generics. Okay, great. So we got all this thing, and now it says Also, we need to fix up the draw method because the draw method is saying forward cards. Yeah, you're right. I want to be able to return forward and reverse cards. Okay? And look at here. There's another four cards. So this is what I was talking about. Our re factoring was a little bit too aggressive, and it changed all these things that we actually didn't want changed. Um, but it did anyway. Okay, so now everything's American. There is an error in the player will get to that. But we haven't really created any reverse cards of all we're creating here is forward cards . Well, here's another place that goes against the advice we had in the slides. Right? We really want to just say card. All right, That's a little bit more generic. All right, So what we're gonna do the requirements say cards that are value number four should be reversed cards. Right. So we can do that by saying, okay, if looks if value equals four. Okay, we're gonna do one thing, Otherwise we're going to do this. But we used to do you might want to do it the other way around and say if values not equal before because kind of the forward card is really the common case, right? Maybe it's better to put the common case at the top. Oops. Sorry about that. And now we just want to change this to reverse car. Okay? Now, you might want to do a little re factory here. See that the drop i'll dot add is the same for both of these. So you could move that out of the block if you want Teoh. Let's not worry about that right now. Actually, they did do that here in this light. So let's do that. I say, Look, both of them have a drawl, piles, not add. So let me move that here and now, because we're the cut, the value the variable card is defined inside these curly braces. It's not visible out here anymore. The scope member of the scope in jobs between curly braces. So you can't You're not able to see this variable. So you actually have to put it up here. It's card card, right? And then you had to use that variable instead of the ones we declared there. So now see how it's highlighting. All four of these cards referred to this exact same variable, right? Whereas before they were, there was an individual card inside of each of the inside each of the blocks. Okay, anyone? That's really not what we're here to talk about. We changed everything, um, to have now some reverse cards and some former cards. And now we need to go to the player class and fix the error that we're seeing there. What's happening? Well, okay, first thing I see is like, Yeah, look, I don't want forward cards. It's just cards. And now it's going to say, Well, wait a minute. It says there's no method cult move in type card. Now you could, and I get this in eclipse just by hovering over the red thing. So we haven't actually never getting back to this problem. We haven't actually added the methods that we need to the card class, right? Or the card interface. Now, this one's kind of cool. I can just click on this and have it do it for me, right? Remember most of the things we had in the slight used the word public in front. It's actually not necessary for interfaces will talk about that when we get back to the slides. But now we've added this method to the card interface. And now, if you remember, what we should do is really we should add that annotation right override to just mark that as like, yes, this is a method from the interface Come. So if we ever go back and let's take a look at it, if I ever for some reason remove this method from the interface, I will get some. Weren't some errors here saying, Hey, you said this is overriding, but it's not okay now. Of course, I don't want to take that up, so I'm gonna leave it back in. All right? And now we get breathy End here number Step 14 says run it and see if see if it works. Right. Okay. So remember, our main method is in sorry. Game right, Good down. Heard above. There's our main method. I'm gonna grab that and let's see if we can get ourselves run as we get ourselves some moving back. We're going to haven't saved class. Sorry. There we go and let's see if they pick dating fours. 563 11 4 Here we go. So starting round two player boot blue. Pick the three and it moved up to square 20 and No. One around three. Player blue picked a four and I went back to square 16. It's working. You can see the players to see any other force here. Not yet. That's running our simulation again and see if we see any other fours. None. This time they were very lucky. Run it again. It's all randomised. So here we go. Oh, here's here's a good one. Player. Green starts in. The first card they pick up is a four, so they have to move backwards through square 59 58 57 56. So they're already behind the go square on the first turn. So probably green lost. We got to the end. Red was on for a blue is on 40 and green was on 19. So Green picked up another four here. That's really unfortunate. So they went back again. So, yeah, they got pummeled in this game. Okay, I hope that makes sense for the the project. Let's go back to the slight, because there's a little bit more I want to talk to you about about interfaces. Okay, So one thing is interfaces can be inherited. So let's go back to what we had in the slides. Remember the contact method interface? Suppose we had another one. We have unauthenticated contact method where you have to log in with the user name password . I can have that interface extend the contact method. So what that means is this interface authenticated contact method has everything that contact Met Method itself has plus these new methods on defining here. So what that means if if I write a class that implements authenticated contact meant that I need to do both of these methods. I need send message from contact method, and I need log in from this one, right? Or else I'll get those compiler errors so you can actually have a whole. We call this a hierarchy. The whole hierarchy of interfaces of like one interface that extends another extends another, um, and combined in different ways. And then you can have your classes implement them. Uh, like so All right. Another feature of interfaces, which is kind of new in the job. A world let's set up to prod the problem here suppose are our card project that we've been working on was an open source platform for building games. And we have lots of people who are using with lots of clients Teoh programmers who downloaded and they build all kinds of games using our framework. It's great, and one of the things they can do is because we have a card in the face. They can implement custom carts. You know, we have forward card reverse card. Maybe they have skipped cards and, uh, you know, go to jail cards or who knows what they might build. And then one day we decide we want to add some more methods to that interface. What's gonna happen? Everyone's code is broken, right? They all suddenly the next time they download the upgrade to our framework. Suddenly the card interface has all these extra methods that they don't have and all their code won't compile. All right, so they're not gonna be happy about that. So if we have this interface card, let's say we had get value and move Azaz interfaces as methods on the card interface. And then one day we decide to add print value. What's gonna happen? All the users code is broken. They'll have to go back and implement print value on every one of their card implementations, or they can't even compile their project anymore. So they're gonna be very, very angry, right? And maybe print value. You wanted to work in a certain way to work with the rest of the framework. Well, they're not really privy to that. And so they might do it in some incorrect manner. Right? So now we have in interfaces as of believe this was added and job eight, this idea of default methods. So remember, up until now, we've stressed that interface methods do not have implementations. It's just the method public into get value, and then a cynical but a default method can actually have some code here. Right? So can of curly braces with some actual real coat. Um, so they actually have an implementation now all they can do here in terms of working with its own interface that they can call these methods right. The interface methods that are declared they can call those methods like this. Um they don't know, for example, any internal state of the of the card itself, like they can't get inside to change things or do anything. All they can do is call these two methods here, so this makes it easy to involve the interfaces so I can add this default method to our card interface. We can ship our framework. Everybody can compile it all works, and they can still override this method. They can still add a print value method to their individual carts if they want to customize the way it works. But they don't have to. That's the point. So this feature was really added because Java ships with the whole set of interfaces for all different types of things in the core library that people have implemented over the decades. And so it made it really, really difficult actually impossible to ever change those interfaces because he would just break the code of tens of thousands of companies right. So now they added default methods and now they can involve those interfaces. And we got a lot of extra new functionality and job eight because of default interface methods. And one last thing We saw this when we did the when we did the code. You don't need the public keyword interface. Methods are always public, so united the keyword, you can do it either way. I kind of prefer to have it there because it makes it explicit, but it is superfluous. You don't doesn't change the meaning of your coded all okay, interfaces. So we know that polymorphism now is a key technique for reducing complexity and allows you to tree eight to treat a lot of different disparate types as a generic type. 14. 10 Inheritance: All right, welcome to Chapter 10 about inheritance. In the previous chapter, we've seen how interface is conserved as polymorphic super types. But we can also use classes for the same purpose. When we do this, we we don't talk about implementing interfaces. We talk about inheriting from classes. So when this chapter will look at jobs, class inheritance and some of the issues that come along with it like abstract classes, constructor chaining, method overriding and several other features. So when you're using interfaces, sometimes it leads to a lot of duplicated implementation. Let's take an example here with our card interface. It has a get value method and therefore the forward card and the reverse card which implement that interface both need to have a get value method. Now we know that it's gonna be implemented the same way right there. Both. They're both of these classes. We're gonna have ah, value attributes a private one, and then we'll have a public getter get value, which returns that attributes, and we do it exactly the same way in both classes. And if we had more classes that implement card, we do exactly the same thing over and over again, and that doesn't seem like a satisfactory solution. So here we're using an abstract card class as the super tight. And so just as a UML note, this solid line the line here has changed from dashed in the previous slide to solid here. That indicates that the super type there, the abstract card is a class instead of an interface. But in this case, what we can do is because we're using class as a super type, we can actually move the code, forget value up into that class, and we can move the private attributes called value up into the class. And we can implement the getter in that class as well. And that way, in the sub classes, in forward card and reverse card, we can inherit that method and we don't actually need to type it out in those classes. Okay, so what does all that mean? A lot of new jargon here. Let's review the jargon first. Okay, so here we see, by the diagram we see there is a super type food and ah, something called Bar that is inheriting from it right now. If we go over her and left the general terms are generalization and specialization, right? Fu is more general. Bar is more specialized, but people use all kinds of words for these, so you'll talk it. You can hear people say super type and subtype with respect to food embargo. Her people talk about the parent and the child, even the ancestor and the descendant. You hear all those words air are fairly well used between interface implementation and class inheritance. But when you're talking about class inheritance, you can also say super class in subclass. Officially, if food was an interface, you wouldn't call it a super class. You'd call it a super type. Although I will say that people in the industry use all of these chart terms almost interchangeably. But I just thought it like, you know, that all of these air pretty much synonyms now What does it mean to inherit from another class? Well, here's what it looks like. So on the left you see the abstract card class and it looks just like a normal class. It's got the inter value and the getter get value, which returns that after Butte and then in order to inherit from the class in the forward card class. Here we used the key word extends and we say extends and then the name of the super class. So it looks a lot like interface implementation, right? Except before we said implements. Now we say extends right. In this case, the abstract court is a super class. The forward card is the subclass, and we said that forward card inherits the get value method. What does exactly does that mean? So let's look at this. We create a class forward card, okay? And then we take that card and we can call get value on it. Now, that's very interesting. If we go back when we look at the forward card class, there is no method called get value here. Right? But you can do this because the get value method, even though it doesn't exist in the four D card class, it exists in its super class in the abstract card class. Right? So when you do this, when you say card dot get value, the code that's executing is the code that's actually written in this super class in this case called abstract card. And this, of course, will be true for all the sub classes in abstract card. In our case, we're talking about reverse card, but there could be more and they would all inherit this get value method. All right, let's talk about how the polymorphism works here. So here we have three different statements, and the 1st 1 of course, is is fine. You can always say forward card card equals new forward card. Any object you can do this way, like class name something equals new class name that always works. But again, we can apply polymorphism here. Remember, that abstract card is the generalization or the super type. So we can put abstract card here on the left as the type of the variable. And then we can create a forward card, and that works fine because afford card is a abstract heart. It is a subtype of abstract card. So this is a fair statement, but it doesn't work the other way, right? This will not compile because an abstract card is not a forward car is a relationship only works one direction. So this is something to remember. The types of your variables, like here on the left, always have to be more general than the actual classes, the specific classes that you're in, stan sheeting and in general and object oriented languages. You want to keep the types of your variables as general as you can, because it ends up simplifying the code and simplifying maintenance quite a bit. But the one time where you really need toe actually specify the precise subclass that you want to use is when you call the constructor. There's no such thing as a polymorphic constructor call. You have to actually type out the name of the class that you want created here. So this is construction. Time is the one time when you really actually need to know whether it's a forward Carter or a reverse card. But after that, you could just refer to it as an abstract card, and it should do the right thing. Okay, overriding methods. So let's say, here's my abstract class abstract card and it's got this nice get value method. But I have a case now where I don't want to use the the behavior from the super class, right. I want to change it. I want to make a rigged card that always returns a specific value. Well, I can do that I can override that method so I can just type in that method again, public and get value. And now I can return my rigged value. So this always returns 42. I could, of course, put any implementation there, and then I tag it with the override annotation so the compiler can check it to make sure I spelled it right. But that's called overriding a method. And in any of the sub classes, you can always decide not to use the super classes implementation for a given method and to write in a new implementation that you want for that class only now, in this case, in the rig card, you've got this new get value forward card and reverse card. Still use the super classmethod from abstract card, right? This doesn't affect them whatsoever. All right, now, with ah super classes and sub classes, there's some interesting questions that come up that don't come up when you're using em interfaces and pay attention to this one. Because when you go for an interview, it's very likely they're going to ask you this question. I generally ask people this question all the time. When I interview them But let's look. There's four different cases here. Well, I want to visit. So let's say I say food object equals new food and then I call object out print. Now notice that both of these have a print method, right? There's a print method in the food class that prince food. And there's a print method in the bar class that Prince bar and bar extends Fu right? And I've tagged it with over right here as well. When I do this, what's gonna happen? Well, I think that one's pretty obvious. It's gonna print food, right? Because that's what foods do. They print food Now, what about this one? I say food object equals new bar. And then I say, object that print. Think about that. Is that gonna print food, or is that gonna print bar? Okay, If you said bar, you are correct now, why is that? This one's the really key one to understand. The class of the object that you created here is a bar because you said new bar When you made the constructor call you, you instructed the Java runtime to create a bar object. This is what bar objects dio right Here's the bar class. So the fact that you gave it the variable, the type food is kind of irrelevant. One way to think about it is that the types of the variables are really for the compiler at source code at company, you know, in the source code for compilation time, but at runtime, What you have are objects like these. These type references don't exist at run time. Okay, so the key thing here is that you created a bar. Now what if we did it the other way? And we said bar object equals new food. What would that print? Well, hopefully your Spidey senses are tingling on this because that doesn't work right? Ah, Fu is not a bar. A bar is a food, right? Food is not extend. Bar bar extends food and you can't have Fu extends bar bark sends food in an infinite loop like that. Like that won't work either. So this is a trick one doesn't work. And then the last one, I think, is probably also pretty easy. If you say bar object equals new bar, what's it gonna print? Well, that's gonna print bar, right? So case number two is the one that is the one that should, if you got that one right, that means you understand polymorphism. And that's great because a lot of people, it takes them a while toe. Figure that one out. If you don't believe me, go ahead and type this code into eclipse or whatever I d. You're using and fiddle around with it and see if you can get it to work and see what happens. Okay, only one super class. So based on that last slide, you might be thinking, Well, this is already getting more complex than interfaces that we didn't have these kind of weird, uh, you know, which method executes questions when we were using interfaces? And yes, that's true. It is more complicated. And if a subclass could extend multiple super classes, then it would really start to get confusing. And there are object oriented languages like C plus plus, for example, where you can have multiple super classes and it does get really confusing. And the way they solve this in Java was to just say, You know what you can only inherit from one other class. This is a fundamental restriction of the job of virtual machine. You can't circumvent it. So whereas when you implement interfaces, you can implement as many as you want and you can just comma separate them. So here we have class Foo implements a comma become See you can go as as many as you like. You'll have to implement all those methods that are specified in A B and C. But when you extend another class, when you use inheritance, you only get one shot. Okay, so you can only extend one super class. You can't say d common that doesn't work. Doesn't matter how good you are. You may be asking, What about Chuck Norris? Can he extend multiple classes? And the answer is no, not even Chuck Norris can do it. So this is a fundamental limitation of java, All right, when should you use inheritance? Now, contrary to the way I motivated this here, you shouldn't use inheritance strictly just to reuse code. Like if you're looking at two classes and saying, Oh, look, they have the same method. Let's let's use inheritance. That's not the right idea. Okay, Uh, only use it when the subclass is a type of the super class, right? when you can say forward card is a type of abstract card or a bar is a food or something like that, it has to work that way. And even more stricter is what they call the list Scott substitution principle or also known as the 100% rule. And that's saying the subclass has got to be able to do 100% of what the super class does without making the client freak out. Right? So what in the world am I talking about here? So let's taken example, This is one that was a hot topic of discussion 20 25 years ago when people were just getting into object orientation. Because in mathematics, we always say, Well, a square is a rectangle, right? And so you might think right away. Okay, Goodman Square class can inherit from rectangle class. And the question I want to ask here is like, Is that really a good idea for object programming? And I'm gonna argue here that new that's not a good idea. And the reason is this. Take a look at this code. Let's say I have ah variable R, which is typed as a rectangle, so I know that the object that that points to is either a rectangle or one of its sub classes, right? I don't know, because I just have rectangle are and I don't need to know because it's polymorphic. Right? So look at this coat, I say Or do I get with and I pull out the current with and then I say are dot get area and I pull out the current area and then I set the width of the rectangle to twice the current with. Now, what do you think is gonna happen to the area from what you know about rectangles? Well, if you take a rectangle double its with with the area doubles to right. But what if that rectangle was actually a square? Suppose we did have this inheritance relationship squares a subtype of rectangle and it's it was a rectangle or equals new square. And then we did this. When you double the width of a square, the height also doubles in the area quadruples. Okay, if this code here that's written in terms of rectangles is expecting the area to double its going to be really surprised when it quadruples, and it might cause it really bad bug. So when you're thinking about polymorphic relationships, subclass super class relationships in an object during a programming language you can't like, that's a different set of constraints than sort of the mathematical constraints about. You know, Square follows the same rules as a rectangle, and if you want to investigate this further, if this kind of intrigues you, there is a practice called Designed by Contract, which was started in this programming language called Eiffel, where you can set what they call preconditions and post conditions basically contracts on the methods, and you can specify at the level of source code how you expect you and your sub classes toe acting. You can prove in that case that a square would not satisfy the contract of a rectangle. Okay, we're not going to go any further into that here. If that's something that interests you, go look up designed by contract, the programming language Eiffel, and it's absolutely fascinating if this stuff seems interesting to you. But in terms of everyday pragmatic programming, yeah, you don't really need to dive into OK, but now you may have a question in your mind. It's like, OK, great So we have to get value method, which is your shared implementation, that all the subclass uses. But what if I have another method that's more like an interface where I want to make sure that all of my sub classes have this method, But I can't. There is no default implementation. It's really more like an interface method. So here I'm saying that Oh my card, No, With their special or not, they all return a Boolean on the is special method. But are they special or inaudible? It depends on the type of the cart, so the method has to go down in Thean Plantation of the method has to go down into the specific type. Great. So how do you do that? Well, that's what we call abstract methods. Okay, so we have an abstract method here, and first we have to mark the class as abstract. That means the class is not complete, and the reason that it's not complete is we have an abstract method. So here's the abstract keyword on the method, which says that I'm declaring this method, but I have no implementation toe offer her Look how it ends with just a semi colon. It looks exactly like an interface method, except for the keyword abstract and actually, in an interface, all the methods or abstract. We just don't have to add the key work, because when the compiler sees that, it's an interface that automatically marks them is abstract. But in a class you do have to say abstract, and we get to this when we have a method in a class that's abstract, there's no implementation for it. So we have to mark the classes abstract to tell the compiler. Hey, you can't create any of these because if you ever called is special, we wouldn't know what to do, right? So when you extend a nab Strack class and now you see why I called the super class abstract card, you have to provide implementations for all of the abstract methods. If you don't think you have to mark your own class as abstract, so it let's say you didn't have in his special here. Then you would say public abstract class forward card extends abstract card, but you have to do one or the other. You have to implement the interfaces where you have to mark your classes abstract. So abstract classes. What's up with them? So first of all there and they're just like interfaces in that they can't be. Instead, she ate it. Okay, However, there different than understates is interfaces in that they can have state. So we saw in our abstract card class. It has that value attributes and has a method called get value, which can access that attribute just like a regular class interfaces can't do that. Okay, so abstract classes can have abstract methods. That's just like interfaces. And they can also concrete methods. Concrete is the opposite of abstract. It means that the method that has an implementation, which is kind of like default methods and interfaces there's still a difference here. In that interface, methods can't access any state of the object, right? They don't have attributes like classes do. All right. Now you might hear the word inheritance hierarchy. This is an inheritance hierarchy, and this is a particularly common one where at the top of an interface. Okay, let's say our card, uh, box here represents an interface, and the interface specifies all the public methods that this whole everyone in this hierarchy needs to conform to now the next level down. We have an abstract class because some of the methods in this case get value, have a implementation which is common across all the sub classes. And so we moved the common code up into the abstract class, so it's only typed in once and then at the bottom. We have the concrete classes at specified that provide all the specific implementations of whatever methods are left in this case, Theis Special method, right? And so, by the way, going back to terminology. This is where people use ancestor and descendant. So from the point of view, let's say a reverse card. The card is an ancestor, right? Abstract card is the parent class card is one of its ancestors and the same thing from the card that the child is abstract class abstract card, but the descendants are forward card in reverse card um, descendants. Really. I mean, it's really just like a family tree, like all of your Children and grandchildren and great grandchildren are your descendants and your parents and your grandparents and your great grand parents are are your ancestors , and we use the words of the same way an object during that, people will say, you know, your grand parent class. Sometimes you hear people say there are grandchild class. All right, Nothing to talk about is visibility. Now. Now we've been using these keywords public and private. Those air called access level modifiers in the job a speck. When we talk about inheritance, we're bringing one Maurin that's called Protected. We haven't seen that yet. We're going to see that in just a minute. And what are these things for? We've kind of skirted that issue through through this class so far, but this is sort of a, uh, security feature that either grants or blocks access to the code, depending where the accessing code lips. All right, so we'll see how this works on the next line. I just want to let you know that with what I'm about to show you about visibility, there's still more to talk about. But we don't. We only need to talk about public, private and protected at this point in time. But in the next part, in part two of the class. Well, there's another way. There's another level of access that we can talk about. Okay, so here's a class with three members, Their attributes private, protected in public. Now I've only showed attributes here because it's more compact to put on the slide. But methods can also be public, private, protected. Okay, so this goes for anything that's inside of a class. It always can be marked with some kind of access level modifier. What do they mean? All right, so it's something is marked private that's only visible from code inside the class. So you see how we have this class, some class, and there's curly brace curly brace. Any code that's written between those curly braces can see this variable. They can actually access the value of it, change the value of it, read the very value of it. Anything code that's outside of these curly braces, like in a different class somewhere cannot gain access to this. So it's it's, ah, hidden inside its private to this class. Okay, by the way, this word member that's kind of popped up out of nowhere. We have attributes like this. We have methods altogether. Those air called members any any kind of entity that lives inside of the class is called a member of that class. It's kind of a generic term. All right, protected protected members can see are visible to everybody who can see private methods. So there are members. They're all visible within the some class curly braces within the scope of that class. But protected members are also visible in the sub classes, right? So if you create another class and said public class, my class extends some class, you would be able to directly access the name attribute that will be visible to you. All right. You would not be able to access the code attributes even as a subclass because it's private , Okay, and then public is what you might think. It's visible from everywhere. So whether you're in the class or outside the class of subclass or any other class, you could see the name attribute and you could assign values to it and read the value of it and things like that. So we use the visibility modifiers. We try to make most of our state private because generally the state needs to be kept consistent, and we don't want external code coming in and mucking around directly with our state because they're probably gonna break it right. And when We're thinking about designing a class that's meant to be sub classed. We use protected methods and protected attributes quite a bit so that the sub classes can access the internals of the class to change its behavior. Right. Designing classes to be sub classed robustly is pretty advanced skill. And there's a lot of books you can read about that. A lot of literature literature out there. Okay, that's a lot of stuff. Um, there's still more to talk about, but let's take a break here and let's go do a little of this in our project so you can see it working. And hopefully that will help to cemented in your brain a little bit. So we left our project in a bad state in that we copied and pasted the code from forward card into reverse card, and we modified one line. That is just an awful way Teoh code. Let's fix that now, so we're going to go into the exercise. What we're gonna do is provide a abstract super class for the cards, and we're gonna move all that common code up into the abstract super class so that we don't have to have it duplicated all over the place. All right, it's a little bit tricky how to do this. Perhaps so you may want to follow the exercise notes if you think you can do it without that, have at it. Um, and once we're done, we'll come back to the slides, and there's a few more topics we need to cover. So if you're not following with the exercises, make sure you stay with the video and forward a little bit to get to the rest of the slides . But for now, let's go into my I D. Which is here, Okay, I don't need the updates and let's take a look at what are Project says. So first thing we're gonna do is move the value attributes. All right, so this is where we put in the work here. We're going to create a new classical, a class called abstract card. We're going to implement the card interface. Uh, that's going to give us a pile over, and then we're going to make an abstract and then hook it up to the sub classes, so that's a fair chunk of work to start with. We're going to create the new class called abstract card? No, if you're if you're looking, you see that I could put the check mark here and make it abstract. I'm not going to do that just cause I want to show you some things in the editor as we go. But in general, you'd probably go ahead and do that. Okay, so we got abstract card, and we said What? We want this to implement car. All right, Great. And hopes Compliments card. And now we get a big fuzzy red line, and it says, uh, abstract heart must inhabit in have implement the inherited abstract method card dot Moves like, Well, I'm not ready for that yet, so let's just make this an abstract class, okay? Now it compiles. So this is just what we're talking about in the slides. Either have to implement the method, or you need to declare your class abstract forward card in reverse card. Now, instead of implementing card, are going to extend abstract card. And again there's an s there. That's right. Card. All right. Um, it's gonna save that. Go over to reverse card now. We don't need implements card here anymore because abstract card implements card. Okay, So we're in an inheritance hierarchy now, like we saw in the slides. And the fact that reverse card extends abstract Hard. An abstract card implements card means that card is still one of our ancestor super types, right? So we don't need to declare it again. You could declare it again in various card. You could say, uh extends abstract card improvements hard. But that's redundant. And generally you won't see that. Okay, back to our instructions here. So we did that and it says, What common code can we move? Well, we can move the value attributes. So it's his move value attribute and delete it from the two step classes. So, in other words, we're talking about this right here we are. Diverse card. Let's take this out Now. This is gonna break a bunch of stuff. So put that there and we go to forward card and we say, Yeah, we don't want that. This is duplicated code. Let's get rid of it. Okay, Great. And it says who? We created a bunch of errors. So what did the air is about? There's air about the subclass code trying to access that value, right? So we're saying Value here. Value here value their, but it can't see it anymore. Right? Um, so what do we need to do? Well, this is because we left it as private. So one changes to protected Say that. And now we've got forward card and we've got verse card and everything's working Now there's another thing here that we see. And this was in the slides that we talked about. We also to get value method. So let's move that as well. Let's go back up to abstract card and we've got this get value method. And we got that there. And then we can remove it from forward card as well. Okay, so we're getting rid of the duplication now. That was trivial, but still, it's duplication. Great. All right, the move method. So this is a little bit more challenging now. What we have here is this move method in forward card, and this move method in reverse card is exactly the same. Except for this method call, right? And so we can't move it to the super class as is. We've got to somehow deal with this with this variation. That's right. Smack dab middle in the middle of our method here and what they're recommending in the in the Klassen, it's here. Exercise notes is to create a new method called Find the following square, given the current score. So what am I talking about here? So I'm gonna here. I have, um, highlighted this section. I'm going to say extracted method here. Let's see if I can get this to work extracted method. Call it. Find following square. Okay. Says the private method that's being called here, and then I can do the same thing in Ford class following many square. So I Okay, I know what I find is that this class in this class, uh, this move method and this move method are exactly the same. Right? So says do the same thing in reverse square and check that the move method is exactly the same. And let's move it to the super class. Okay, Now, you can also expect that this is gonna leave you to some errors, right? So But let's first get this going. Take that and we go to abstract card and we put the move method up here. Okay. Great. Well, so we've got a problem right away. Well, hold on before we do that. Got it There. Good. Reverse card. Let's take the move method out. Because now it's in the super close. All right. Looks good. And this is yellow. It's saying, Hey, nobody ever calls this method and an abstract card. It's saying I don't know what this method is. So you guys know what the answer is to that? We need to put an abstract method in the super class. Right. So what we're saying here is that all the sub classes we're gonna need to tell me how to get to the following square. Sometimes you go forward, sometimes you go back. Maybe there's other implementations you can think of. But what we're gonna do here is protected because we want this to be visible in this up classes abstract square, fine. Following square. Uh, square coming. I guess we could call it position. Doesn't matter. Okay, great. So now my abstract card classes happy? This is exactly how you would do it. But now these two guys were broken. What are they complaining about it saying? Well, you can't reduce the visibility. So what that means is this method is protected. Uh, you can make a protected, you can override a method that's protected with, um, keeping it protected. Or you could make it public. But you can't hide it. You can't make it private. So we need to change this to protected. We didn't know that when we started, but that's okay. And while we're at it, that said the override just to make sure we didn't mess up, okay, it didn't turn red. So that means we've spelled it right and the same thing here. Let's make this protective and let's put in and over right here. Okay, good. So now we've got all these things. Uh, we've got the over an annotation. Let's run our game just to make sure it still works in that we didn't break anything. Okay, there we go. On we look at our console. We see that looks like it's working correctly now that the technique we used here, where you, um, create an abstract method, it's called from the middle of of the super class method is called. It's actually a design pattern called the template method pattern, where the move method is the same for all the sub classes. But there's a step right in the middle, like how you know which is the next square to go to. That varies according to whether it's a forward card or your scarred right. So this is called the Template Method. Move is a template method. This is called fine falling scores, called a hook method. And then in the sub classes you implement the hook method, right? So one is previous square when you're going backwards, if you're going forward to go next square. So that's a pretty nifty object. Iran did implementation of this little problem. We have this complicated move method which is now at one place in the super Class. We don't have any cut and paste, and the reverse card in the forward card now contain unique. Very nice. All right, let's go back and let's finish our exercise. So we have a couple more topics to talk about here. So, first of all, um, one thing we didn't quite clean up yet are the instructors. And that's because God talk about constructor inheritance and what the deal is that constructors are not inherited, right? So here we've got a food class with the constructor, takes an integer and then we have a bar class with extends food and we want to do something like this one to say OK, it's creating new bar and passing the number five right cause it's got a constructor that takes uninjured, right? So that should work doesn't work, right? That's compiler error. And in fact, because constructors air not inherited doesn't matter what constructors exist in the super class. The compiler looks at the bar class. It says, Oh, you didn't supply constructor. So I'll give you a default constructor. Remember that compiler generates to fall constructors. That's all you have. So you can't pass parameters into Well, that's not good, because we want this attributes value to have something there. It shouldn't just be zero like we want to pass some numbers into it. Right? Let's take another shot. Let's say we do something like this. We just copy and paste the constructor in the subclass. We had to change it from food to borrow because the name of the constructor always has to match the class name. Wait. Okay, surely this works, right? Ah, well, that doesn't work either. All right, So what's going on here? The bottom line is that the super class state needs to be initialized in this place. We have this this attribute called value that needs to be assigned something. Um, however, as in this case, a lot of times, the subclass can't see the super class state because it's private, right? Like, how are we gonna set value? Like even if this failed, this statement would fail because we can't actually see value. It's private. How am I going to initially is let state? Well, how do you usually initialize state with the constructor call? Right. So what we're gonna have, what we're gonna find out is every subclass constructor it's gonna have to call a super class constructors. So this constructor here is going to figure out how to call that constructor there and pass the value in in order for it to initialize that attributes may. And if you don't specify which super class constructor to call, it calls the default constructor. So what's happening here? We didn't write any special code here in our constructor to say which super class constructor to call. In fact, I didn't show you how to do that yet, So the compilers looking at this and saying, Oh, you must want to call the default constructor on class few. Well, class Who doesn't have a default constructor? Because look, we wrote an explicit constructor. And remember, if you write an explicit constructor, the compiler no longer generates a default constructor. So this is broken at every level, right? And the error message you're going to get is you'll be working in the bar class. This will turn rant, and it'll say class food is don't have a default constructor and you'll be like, What? I'm not working in class food. Like Why? Why am I getting errors of that class food? All right, how do you fix this? 15. 11 Conclusion: Okay, welcome to the conclusion of part one of Professional Java, Chapter 11. So congratulations. You finished part one of this three part series where we talked about basic java and object orientation just as a review just to remind yourself of all the things you worked on. You did a lot of hard work in this part. We went over the we install job and went over the basic architecture and Java ecosystem. We talked about development environments and installed one of those for our projects after the hello World Project and a little bit of review of syntax highlights and fiddling with that, we jumped into the meat of the of this part which was classes and object oriented design we used to raise. We used collections. We built polymorphism polymorphic calls using interfaces, and then we extended that to use inheritance and abstract classes. So you've seen a large fraction of the object oriented power of Java so far. If you're still on board and you want to learn some or part two will work on the mechanics of Java. So the core language features that are still part of the structure of the language but are not really object oriented per se. And then a bunch of the core libraries that job the ships with some of the key ones will be looking at because those air really integral to your day to day work. So if that sounds good to you, I will see you in part two. And thanks so much for getting through Part one. I really appreciate it. I hope that was interesting for you. And we'll see you in part two by now.