Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5
Let's take a look at classes and objects.
In this lesson, we're looking at the ways in which we can
model business problems with classes. Java is an object-oriented language, so obviously we pro duce classes. And we create instances of these, and these instances, they would reflect the actu al sort of business data, and they will reflect business objects that interact with the program, invo ke methods upon each other. To reference current instance, we'll use the keyword "this." So we'll learn how to use that. We als o need to understand the general process of object instantiation, distinguish different types of var iables, like local variables, or instance variables, or static variables, and actually distinguish gene rally the difference between static and instance context, and invoke operations, axis variables. And from this lesson onwards, we'll be doing exercises not in a JShell tool, but in NetBeans. So that's an IDE, Integrated Development Environment, and we'll use that to produce our further code and our projects. Let's start with the approach to how you de cide which classes you need in the first place and what this class is supposed to be doing. That's done through modeling of the business problem at hand, what it is that you need to design, what kind of code you need to design, and exactly how. And the primary way of producing these models would probably be UML, Unified Modeling Langu age. There are lots of different UML diagrams available for you to reflag different aspects of the s ystem architecture and design. Now, this course does not really have an objective to cover, the U ML model, in any detail. For that, you actually have another course, Object-Oriented Analysis an d Design Using UML, which you may wish to look into, which is rather interesting in terms of just how you do the analysis, and how you reflect the business requirements as various models, and how you do the design of your software. But in this particular course, we are trained here to be programmers. Now, programmers are not necessarily doing all the design analysis, but they certainly need to understand the design and analysis artifacts, because they need to be able at least to read the se diagrams, and they need to be able to communicate with analysts and designers the ideas of what the code is supposed to be doing, how it's supposed to be working. So at least some conce ptual level of what UML diagrams represent is probably required. So here's just some examples of UML models, like use case models that illustrate general use ca ses of the program, what it is supposed to be doing, what classes you need to model, class diagr ams, various forms of diagrams that show the algorithm of the program. This could be activity mo dels. This could be sequence models. Either way, they illustrate the logic of what the program is doing. There might be a requirement to model the state of the program and a transition, how the object goes from one state to another. There might be requirements to model deployment topology, whi ch piece of software is deployed where, especially in distributed systems. That's rather important. So there are lots of different UML diagrams. Now, we'll take a look at a couple of these diagrams, for example, the class model. So that model allows us to see what classes we need to create-- what, shop, product, drink, food, whatever our classes we need to produce-- and then what attributes these classes would have, like ID, name, price, best before. These are attributes of the product, or price lists might be an attribute of a sho p, et cetera. So attributes and operations, methods, that these classes need to have, so, for exa mple, on a product, get ID, get name, et cetera, apply discount. In a shop, maybe add products, I don't kno w, get price lists, something like that, et cetera. The diagram could also demonstrate the relationship between different classes. For example, if s hop references products, well, you could basically designate that there might be multiple product s sold in a shop, and also, a hierarchical relationship between classes. Remember, classes form class hierarchies, so parent/child relationships, like for example, between drink and product, food and product. So a diagram shows that drink and food are subclasses of product, subtypes of pro duct. So that's generally what-- roughly what you expect the class diagram to illustrate. The symbols, like pluses and minuses, may be used to show axis modifiers, like private or public. And then variables will obviously indicate the return-- variables indicate their type. Methods could indicate return types and parameters. There you go. So it's a comprehensive model of what the design of your classes ought to look like. Now, another type of model that I would like to quickly show you is actually two types of models, t he activity and sequence diagrams. The reason why they're side by side on the same page is be cause they actually illustrate similar aspects of the system design. The activity model represents a flow of operations. So you have some kind of event that triggers the activity flow, and then you i nvoke operation method process products. Then you get best before, and then you may have some choices as to which way your program goes from here. Sequence diagram-- well, it sort of illustrates a similar premise as in the logic of the program, but it focuses on how one method invokes another. So we're looking at the process product calls the get best before. That returns the value. Then it calls apply discount, and in which class, upon whi ch class, the method invocation is performed. So, for example, get best before is a method of a product that you can actually see from the clas s diagram, and a shop invokes it. Apply a discount does is another method of the product-- shop invokes it. Remove product is a method of a shop itself, and so you can see it's kind of recursively invoked on the same class. So it helps you to appreciate the relationship not just between classes in general, but also the flo w of the program, the sequence of activities, what it is that your program actually needs to perfor m in terms of its algorithm. And these and many other diagrams constitute your application desig n. So these are just some examples. Based on whatever your application designers and analysts figured out, you'll start writing code. Your actual Java classes will reflect findings of class diagrams and the algorithms you place into your methods. It should reflect the findings of various types of activity or sequence diagram mode ls. So how do you go about actually writing class code? Well, the syntax goes like this. You describe the class, which is a member of some package. Theoretically, you can describe the class that it belongs to a default package, but that's really not recommended. Package is a unique name sp ace against which you group your classes. So package name, and then you may have import statements. We import other packages or othe r classes, but that's optional. And then you could have the class definition itself which starts with an axis modifier, then the keyword class, then the class name, followed by the actual body of the class. That's the general syntax. And here's an example. I've got this class product, public class product. It sits inside a package, demos shop. It uses the class big decimal from Java math. So we have an import here. And then the body of the class would follow. And there, you have your variables, methods. What ever other code you want to write, well, you put it into the body of this class, whatever code belon gs to that class according to your models. Now, how do you create an instance? How do you instantiate that class to create an actual object? Well, that's done with a new operator. To create an instance, you call new, and then invoke that class, new, and which class you want t o instantiate, followed by round brackets. Now, we'll see why we put this round brackets in a mo ment, which is apparently significant. But for now, that's how you create an instance. Now, when you create an instance, new product, you actually allocate memory to store that prod uct. It doesn't have any values just yet. Maybe there's no actual value for price, but it's certainly c apable of having that price. Why it's capable of having a price? Because it actually has an instance variable that says, well, bi g decimal price, yes. So potentially, you can assign some value to the price. When you just create a product like this, the value is not necessarily assigned immediately. Ther e is no default initialization. So the price is not initialized. But then we call a method set price. Hmm, hold on a second. But what do we call this method upon? So when you created a new pro duct, OK, you allocated memory. You placed that memory structure somewhere, but then you ne ed to be able to access that memory. So what you do is create a reference. A reference is a variable. In this particular case, p1, and thi s variable is of a compatible type. So if you creating an instance of product, the variable, I guess, well, type of product as well. Doe s it always have to be exactly the same as the class you're instantiating? No, not necessarily, but it ought to be compatible type, and we'll discuss that compatibility again a little bit later. So you have a variable, which you initialize, and this variable references the memory area where you actually allocated that object. And then through that variable, using the dot operator, you can start accessing that memory area. And telling, what do you want to do, invoke methods, access v ariables if required? So in this particular case, we're invoking the method set price, setting it to 1. 99, and then we're getting the prices, retrieving it back from that memory area. OK, well, that's th e gist of how you create an object, an instance of appropriate type here, in this particular case, a n instance of product, and how you access that instance. Now, when you define instance variables, you consider, first of all, the fallen syntax. Instance vari ables are having an axis modifier, variable type, variable name, and maybe initialize to a certain value. You have instance variables within your class definition. You define your instance variable s within a class definition to describe what data structure each and every object of that type of th at class should have. In other words, you're saying every product should have an ID, name, price, best before. You ma y initialize these values immediately. Like in this particular case, best before is initialized as three days from now-- local date now plus three days. But you don't have to. You may initialize these v ariables later, so long as you initialize them before you use them, I guess. Now, so every instance of the product, every time you create new product, you would be able to f or that product set a different value of ID, set a different value of name price, et cetera, et cetera, or best before. So that's why we call these instance variables, because each of these variables will have a relations hip to a specific instance of that class, to specific instance of product. Now, if you do initialize the variable, then, well, it will have whichever value assigned to it. But what if you don't? Well, you see, the interesting thing is that these variables, instance variables, are going to be def aulted. If the instance variable is a primitive, which is a number like int, float, double, or whatever, or char, is defaulted to 0. If its Boolean, it's defaulted to false. So if these are primitives, their values would be 0s, and in case of the Boolean, false. If the varia ble is an object-- string, big decimal, local, date-- well, you know, anything else but the eight primi tives basically, then its default value is null-- not referencing any memory unless you explicitly sa y which memory your referencing. So best before references, this local date object, for example. So instance variables apparently are defaulted. Good. So, well, of course, you can initialize them explicitly, but if not, then that's the way the product will come out when he just create a new insta nce of it. Now, you may describe not just variables, but also operations, methods, that will have a context of a specific instance of that class, specific instance of product. For each method, you describe it s axis modifier, its return type, the method name, and then the list of parameters. List of paramet ers is described as parameter type, followed by parameter name, and that's comma-separated. If the method promises to return certain value, then the last statement in the method should be a return statement. So it must return something of appropriate type that this method promised to re turn. The method, however, could be declared with a void return type, in which particular case, w ell, you don't need to return anything. You're not promising to do any return from the methods, an d you don't have to. You don't have to put the return state in this case. Actually, you can still return from the void method by just putting return and then semicolon, kind of empty return statement, if you just wanted to terminate the method, but that's not required. A r eturn statement is actually required only if you really promise to return something, like this metho d get name that promises, whoever calls it, to return string. And obviously, what you need to mak e sure you do is you return appropriate type. Now, there are a couple of things you probably noticed, that these variables and methods, variabl es on previous page, and methods on this page, they're all associated with access modifiers, right? Well, it's considere d to be a good design practice to make your variables generally private and methods public. We'l l discuss later why is this the case. And no, you don't have to do it. You may create public variables if you like, and there are other a ccess modifiers you could use. But for now, let's just assume as a rule of thumb that you probabl y would prefer hiding variables inside a given object and then exposes some operations that othe rs can invoke, can manipulate these variables, with these operations. So operations tend to have a wider access modifier than variables, and it's typically variables private and operations public. L ater on we'll discuss more of that topic, and we'll find out exactly why this is a recommendation. Now, talking of parameters, if method does not have any parameters, then just leave empty roun d brackets. You still have to put parentheses. You still have to put round brackets even though yo u don't put anything inside. If method dose have parameters, well-- type, name, comma, next, type, next, parameter name-- as many as you like. And, of course, then after that, the method would have a body. Open, and cl ose, and curly brackets designate where is the start and the end of the method. Naming convention-- variables, typically nouns, methods, typically verbs. Well, at least starting fr om verb, and as you could see, using a mixed case to define these. Now, a little bit more about the actual process of creating and initial izing objects, so create an instance. That's right. So the new operator creates an object, creates an instance of a certain type, of a certain class. It actually allocates physical memory. So you could say, new product like this-- n ew product. You are not obliged to assign a reference to reference that memory. Sure, you can, and you prob ably should. But do have to? Technically, not really. So you can just allocate the memory for the product and not really reference it in any way. OK, w ell, let's take a look at the definition of the product class. It has a variable name, but it doesn't real ly set the variable name to anything, right? There is no default value. It doesn't say, name equals something. So by default, the name is just null. What about the other cases here? So we create product, p1, new product. A little bit later, will we use p1 to set the name-- set name t. So initially, it will also be null. But then because we're assigned that instance of the product to ref erence, now we can access that memory through the reference, and set the name variable, invok e that method set name. And then we'll grab the parameter we're passing and assign it to that ins tance variable for us. So the product will have a name, tea. I have another product, p2. And I assign a reference to it. So new product, and assign it to variabl e p2. However, here's an interesting thing. I can actually create a second, third, fourth, whatever, refer ence, reference in same memory area. That is allowed. I know that looks strange. Why would you do something like that? But it's possible. And we'll actually have a use case for it a little bit later. So for now, let's just establish the fact that any given object in memory can be referenced by mult iple different variables. That's perfectly normal. You could do it. So when I go and say, p2 set name, cake, I said it to that memory area. But because p2 and p3 a re essentially two references, reference and exact same object, it doesn't matter via which refere nce I'm accessing it. I could say p2 get name, and that would get me cake. Or I can say p3 get n ame, and it will also get me exact same cake. So in this particular case, when I run this program, this is the output that I'll see on a console printing, tea in a cup, cake on a plat e, and cake to share, because it's basically saying cake again. Now, interesting thing is, that if I tr y to write code p1.name, like this, and assign something, like coffee, for example, I will fail. Comp iler will not allow this line of code. Why? Because the variable is private. It prevents me from modifying it from outside of the class product. Inside a class product, I could say name equals whatever I like, you know, just assign something that's within the class product. But inside a class shop, it's a different class. I cannot access the variable name directly. I actually have to use methods, like get names, set name, that were made public, that were made available for all the classes. I have to use these methods to manipulate with these names-- whatever internal data the product has. If you think about it, the method could perform other actions. It doesn't have to just take the parameter and assign it to a variable. It doesn't have to just return the value. That might be-- the whole algorithm could be written inside these methods. So you can write mor e logic, and this logic could check what a parameter value is, validate it, modify it, derive things, f ormat things differently, something like that. So these methods could contain some code. And, of course, if you allow variable to be assigned directly, then he can't possibly guarantee that the cod e of your methods will actually be properly invoked, because then the methods could be bypasse d. And hence, the reason why the variable could be marked as private, to ensure that from outsid e of the class product, whoever tries to manipulate it with a product name, or, well, for that matter, any other variables so you can model into it, they actually have to invoke methods that you've made public so you guara ntee that whatever logic you place into these methods will be properly triggered. So what we've learned from this page, once again, is that new operator allocates memory. You c an assign a reference to reference that memory. Through the dot operator, you can invoke metho ds, and these variables are public access variables as well. And then you can potentially create more than one reference, reference in the same object in your memory. So that that's plausible. We'll still have to discover why we want to do that and what are the circu mstances when that happens. But so far, so good. We're just covering the syntax first.
Agile Project Management And Requirements Gathering: Learn the Scrum agile Framework Including Agile Release Management, Scaling And Psychology Of Scrum Teams
Instant Access to (Ebook) Object-oriented software development using Java: principles, patterns, and frameworks / by Xiaoping Jia. ISBN 9780201737332, 0201737337 ebook Full Chapters
Agile Project Management And Requirements Gathering: Learn the Scrum agile Framework Including Agile Release Management, Scaling And Psychology Of Scrum Teams
Instant Access to (Ebook) Object-oriented software development using Java: principles, patterns, and frameworks / by Xiaoping Jia. ISBN 9780201737332, 0201737337 ebook Full Chapters