Tuesday, April 2, 2019
Modern Programming Tools And Techniques Computer Science Essay
Modern Programming Tools And Techniques Computer Science potentiometervasQ1 Define generality, encapsulation, modularity and hierarchy in your bear terms.Ans-AbstractionAbstraction denotes the all important(p) characteristics of an endeavor that differ it from early(a) goals, and thereby providing a boundary that is congenator to the perspective of the catch up wither. Abstraction focuses on the asideside-view of the Object, and helps separate its demeanour from its implementation, Think of it this air, to you, your railway car is an utility that helps you commute, it has a steering wheel , brakes etc except from an engineers rase of view the very same car represents an entirely diverse view point, to the engineer the car is an entity that is composed of sub elements such and engine with a certain horse power, a certain cubic capacity, its power mutation ratio etc. It is the same car that we ar talking about, except its sort and properties give birth been encaps ulated to the perspective of the viewer. This is what abstraction is.EncapsulationEncapsulation is breaking down the elements of an abstraction that constitute to its structure and port. Encapsulation serves as the interf sense experience between abstraction and its implementation.To meet encapsulation better, lets consider an animal such as a dog. We know that a dog barks, it is its sort, a property that gear ups a dog, yet what is hidden is , how it barks, its implementation, this is encapsulation. The hide of the implementation details of a behavior that defines a property of an entity is Encapsulation.ModularityThe device of partitioning a program into individual comp wizardnts so as to goinguce its complexityto some degree croup be termed as Modularity In addition to this, the division of the work out into modules helps provide clear boundaries between several(prenominal)(predicate) parts of the program, thereby allowing it to be better documented and defined. In ot her words Modularity is building abstraction into discrete units. The direct bearing of modularity in deep brown is the use of packages. Elements of Analysis and DesignHierarchy (heritage)Abstraction is good, but in most real universe cases we find more(prenominal) abstractions than we can comprehend at unitary time, though Encapsulation will help us to hide the implementation, and modularity to crisply cluster logically related abstractions, at times, it good isnt enough. This is when Hierarchy comes into the reckon, a set of Abstractions together form a Hierarchy, by find outing these hierarchies in our design we greatly simplify our understanding of the problem.Single InheritanceSingle Inheritance is the most important part of is a hierarchy. When a phratry sh atomic number 18s thestructure of another formify it is said to single inherit a base air division. To understand the concept better, lets try this. Consider the base split Animal. To define a bear terms of and animal, we say a swordplay up is a kind of Animal. In simpler terms, the bear single inherits the structure of an animal. duplex InheritanceMultiple Inheritance can be defined as a part of inheritance where the sub curriculumes inherit the Behavior of more than geniusness base type.Q2 Sketch the intention-oriented design or the Card high Black-Jack. What are the key objects? What are the properties and behaviours of these objects? How does the object interactAns-Blackjack capital punishmentIt must write three current configurationes and link them with all of the preceding gradationes in the project. The first variance, DealerHand,implements the algorithm of playing Blackjack from the dealers perspective.The classcontains a field of study which keeps track of the current number of points in a batch, and a modethat calls in a counter-controlled loop the method of the previous class GameDeck to deal separate one at a time from the sink of the deck. As card are bein g dealt, the current number of points in the hand is updated accordingly. other method of GameDeck requites the treasure of the above field.The next class, PlayerHand, is a subclass of DealerHand. It overrides the methodfor transaction cards the cards are still dealt in a loop, but the loop is sentinel- controlled thistime, and the method incorporates interaction with the user.The third class, GameApp, contains the method main in which objects ofDealerHand and PlayerHand are created. Methods for dealing cards are invoked on theseobjects. When these methods return, the winner of the gimpy is determined according tothe normal Blackjack algorithm.The specific details of the algorithms for calculating points in each(prenominal) hand and fordetermining the winner of the crippled are figured out by students with practically noassistance from the instructor. By this point in the course, the students are able to writethis code independently, fashioning use of the techniques, concep ts, syntax and basicstructures of the Java language that they have learned during the semester.While the application could be created using any development environment, Ibelieve that its victor in my class is dependent upon the use of BlueJ. BlueJ enables thisproject in devil ways (1) as a very simple-to-use tool for writing and redaction code, and (2)through the provided sample code that allows users to create images onscreen without anyprior noesis of Java graphics (e.g., the Swing API). Because BlueJ minimizes thehurdles associated with graphics programming, novice students are able to create aninteresting and fun application, which helps them master the basics of the object-oriented attack in the earliest stages of their CS coursework.As an example, suppose you want to write a program that plays the card game,Blackjack.Youcan use the Card, Hand, and Deck classes developed. However, a hand in the game of Blackjack is a little different from a hand of cards in general, since it must be possible to compute the grade of a Blackjack hand according to the rules of the game. The rules are as follows The shelter of a hand is obtained by adding up the fosters of the cards in the hand. The value of a numeric card such as a three or a ten is its numerical value. The value of a Jack, Queen, or King is 10. The value of an Ace can be every 1 or 11. An Ace should be counted as 11 unless doing so would put the total value of the hand over 21.One way to handle this is to extend the living Hand class by adding a method that computes the Blackjack value of the hand. Heres the definition of such a classpublic class BlackjackHand extends Hand public int getBlackjackValue() // Returns the value of this hand for the// game of Blackjack.int val // The value computed for the hand.boolean sensation // This will be set to sure if the// hand contains an ace.int cards // Number of cards in the hand.val = 0ace = falsecards = getCardCount()for ( int i = 0 i // Add the value o f the i-th card in the hand.Card card // The i-th cardint cardVal // The blackjack value of the i-th card.card = getCard(i)cardVal = card.getValue() // The normal value, 1 to 13.if (cardVal 10) cardVal = 10 // For a Jack, Queen, or King.if (cardVal == 1) ace = dead on target // There is at least one ace.val = val + cardVal// Now, val is the value of the hand, determine any ace as 1.// If there is an ace, and if changing its value from 1 to// 11 would leave the score less than or equal to 21,// thusly do so by adding the extra 10 points to val.if ( ace == true val + 10 val = val + 10return val // end getBlackjackValue() // end class BlackjackHandQ3 Sketch the object-oriented design of a system to control a soda water dispensing machine. What are the key objects? What are the properties and behaviours of these objects? How does the object interact?ANS-The aver machines interface is encapsulated in the peignoir class. The wrappee hierarchys interface mirrors the wrappers interf ace with the exception of one additional parameter. The extra parameter allows wrappee derived classes to call back to the wrapper class as necessary. Complexity that would otherwise drag down the wrapper class is neatly compartmented and encapsulated in a polymorphic hierarchy to which the wrapper objectdelegates.ExampleThe fix pattern allows an object to change its behavior when its internal state changes. This pattern can be observed in a vending machine. Vending machines have states based on the inventory, tote up of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is made, a vending machine will either receive a product and no change, hark back a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventorydepletion.Identify an existing class, or create a new class, that will serve as the state machine from the clients perspective. That class is the wra pperclass.Create a republic base class that replicates the methods of the state machine interface. Each method takes one additional parameter an instance of the wrapper class. The State base class specifies any useful defaultbehavior.Create a State derived class for each domain state. These derived classes only override the methods they need tooverride.The wrapper class maintains a current Stateobject.All client requests to the wrapper class are simply delegated to the current State object, and the wrapper objects this pointer ispassed.The State methods change the current state in the wrapper object asappropriate..public class VendingMachine offstage effigy sales private int cans private int bottles public VendingMachine() fillMachine() public jazz fillMachine() sales = 0 cans = 10 bottles = 5 public int getCanCount() return this.cans public int getBottleCount() return this.bottles public double getSales() return th is.sales public void vendCan() if (this.cans==0) System.out.println(Sorry, out of cans.) else this.cans -= 1 this.sales += 0.6 public quiet void main(String argv) VendingMachine machine = new VendingMachine() Part BQ4 In an object oriented inheritance hierarchy, the objects at each level are more specialized than the objects at the higher levels. Give three real world examples of a hierarchy with this property.ANS- Single InheritanceJava implements what is cognise as a single-inheritance model. A new class can subclass (extend, in Java terminology) only one other class. Ultimately, all classes eventually inherit from the Object class, forming a tree structure with Object as its root. This picture illustrates the class hierarchy of the classes in the Java utility package, java.utilThe HashTable class is a subclass of Dictionary, which in turn is a subclass of Object. Dictionary inherits all of Objects variables and methods (behavior), then adds new variables and behavior of its own. Similarly, HashTable inherits all of Objects variables and behavior, plus all of Dictionarys variables and behavior, and goes on to add its own variables and behavior.Then the Properties class subclasses HashTable in turn, inheriting all the variables and behavior of its class hierarchy. In a similar manner, Stack and ObserverList are subclasses of Vector, which in turn is a subclass of Object. The power of the object-oriented methodology is apparentnone of the subclasses necessary to re-implement the basic functionality of their superclasses, but needed only add their own specialized behavior.However, the above diagram points out the minor weakness with the single-inheritance model. Notice that there are dickens different kinds of enumerator classes in the picture, both of which inherit from Object. An enumerator classimplements behavior that iterates through a collection, obtaining the elements of that collection one by one. The enumerator classes define behavior that both HashTable and Vector find useful. Other, as yet vague collection classes, such as list or queue, may as well as need the behavior of the enumeration classes. Unfortunately, they can inherit from only one superclass.A possible method to solve this problem would be to leaven some superclass in the hierarchy to add such useful behavior when it becomes apparent that more subclasses could use the behavior. Such an approach would lead to topsy-turvyness and bloat. If every time some common useful behavior were necessary for all subsequent subclasses, a class such as Object would be undergoing constant modification, would grow to enormous size and complexity, and the specification of its behavior would be constantly changing. Such a solution is untenable. The elegant and feasible solution to the problem is provided via Java interfaces, the subject of the next topic.Multiple inheritanceSome object-oriented programming languages, such as C++, allow a class to extend two or more superclasses. This is called three-fold inheritance. In the illustration below, for example, class E is shown as having both class A and class B as direct superclasses, while class F has three direct superclasses.Such multiple inheritance is not allowed in Java. The designers of Java wanted to keep the language reasonably simple, and felt that the benefits of multiple inheritance were not worth the cost in increased complexity. However, Java does have a feature that can be used to accomplish many of the same goals as multiple inheritance interfaces.Class hierarchiesClasses in Java form hierarchies. These hierarchies are similar in structure to many morefamiliar classification structures such as the organization of the biologic worldoriginally developed by the Swedish botanist Carl Linnaeus in the 18th century. Portionsof this hierarchy are shown in the diagram . At the top of the chart is theuniversal categor y of all living things. That category is subdivided into severalkingdoms, which are in turn broken down by phylum, class, order, family, genus, andspecies. At the bottom of the hierarchy is the type of creature thatbiologists name using the genus and species together. In this case, the bottom of thehierarchy is occupied by Iridomyrmex purpureus, which is a type of red ant. Theindividual red ants in the world correspond to the objects in a programming language.Thus, each of the individualsis an instance of the species purpureus. By virtue of the hierarchy, however, thatindividual is in like manner an instance of the genus Iridomyrmex, the class Insecta, and the phylumArthropoda. It is similarly, of course, both an animal and a living thing. Moreover, eachred ant has the characteristics that pertain to each of its ancestor categories. For example,red ants have six legs, which is one of the defining characteristics of the class Insecta.Real example of hyrarchyQues5 How do methods Syst em.out.print() and System.out.println() differ? Define a java constant equal to 2.9979 X 108 that approximates the speed of light in meters per present moment.ANS-1) public class bowlpublic static void main(String args)int length = 10int width = 5// calling the method or implementing itint theArea = calculateArea()System.out.println(theArea)// our declaration of the methodpublic static int calculateArea()int methodArea = length * widthreturn methodArea2) public static void printHeader()System.out.println(Feral Production)System.out.println(For all your Forest Videos)System.out.println(427 Blackbutt Way)System.out.println(Chaelundi Forest)System.out.println(NSW 2473)System.out.println(Australia)System.out.println(String argument)System.out.print(String argument)In the first case, the code fragment accesses the println() method of the object referred to by the class variable named out of the class named System. In the second case, the print() method is accessed instead of the printl n() methodThe difference between the two is that the println() method automatically inserts a newlineat the end of the string argument whereas the print() method leaves the discover cursor at the end of the string argumentDefine a java constant equal to 2.9979 X 108 that approximates the speed of light inmeters per second.Floating-point values can also be written in a special programmers style of scientific notation, in which the value is represented as a floating-point number multiplied by aintegral power of 10. To write a number using this style, you write a floating-point number in standard notation, followed immediately by the letter E and an integerexponent, optionally preceded by a + or sign. For example, the speed of light inmeters per second is approximately2.9979 x 108which can be written in Java as2.9979E+8where the E stands for the words times 10 to the power.Boolean constants and character constants also exist and are described in subsequent chapters along with their c orresponding types.Q6 lay aside a code segment that defines a Scanner variable stdin that is associated with System.in. The code segment should than define to int variables a and b, such that they are initialized with the next two input values from the standard input stream.Ans-Import java.util.* commonplace class mathfunPublic static void main(string args)Scanner stdin=new electronic scanner (system.in)System.out.print(enter a decimal number)Double x=stdin.nextdouble()System.out.print(enter another decimalnumber)Double y=stdin.nextdouble()Double squarerootx=math.sqrt(x)System.out.println(square root of +x+is+square rootx)System.out.println(PersontHeighttShoe size)System.out.println(=========================)System.out.println(Hannaht51t7)System.out.println(Jennat510t9)System.out.println(JJt61t14)Q7 Separately identify the keywords, variables, classes, methods and parameters in the following definitionimport java.util.*public class runningpublic static void main(String args)Scanne r stdin = new Scanner(System.in)System.out.print(Number)double n = stdin.nextDouble()System.out.println(n + * + n + = + n * n)Ans- public static void main(String args)-methoddouble n = stdin.nextDouble()-variablespublic ,static, void ,-keywordsstdin println-keywordtest -classdouble-parameters
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.