OBJECT 1 ORIENTED PROGRAMMING

Size: px
Start display at page:

Download "OBJECT 1 ORIENTED PROGRAMMING"

Transcription

1 OBJET ORIENTED PROGRAMMING hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN.

2 Objectives You will learn: Features/facilities of creating a class in Java. Defining class and its members. Scope and lifetime. Managing inheritance in Java. Overriding method. Super object. loning objects. Writing abstract classes and methods. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page i

3 lass reation There are two primary components which make up the implementation of a class the class declaration class body The class declaration declares the name of the class along with other attributes. The class body follows the class declaration and is embedded within curly braces { and. The class body contains declarations for all instance variables and class variables. Instance and class variables collectively are referred to as member variables for the class. The class body also contains declarations and implementations for all instance methods and class methods for the class. Declarations and class methods collectively known as methods. A class may contain one or more constructors that provide for the initialization of an object created from the class. A class's state is represented by its member variables which are declared in the body of the class. Typically, a class's variables are defined before its methods are declared. classdeclaration { member variable declarations method declarations To declare variables that are members of a class, the declarations must be within the class body, but not within the body of a method. Variables declared within the body of a method are local to that method. Objects have behavior that is implemented by its methods. Other objects can ask an object to perform something by invoking its methods. In Java, a class's methods are defined in the body of the class for which the method implements some behavior. Typically, a class's methods are defined after its variables in the class body. Member variables and methods are known collectively as members. When declaring a member of a Java class, access specifiers can be used for allowing or disallowing other objects of other types access to that member. A Java class can contain two different types of members: instance members class members SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

4 lass Declaration lass Declaration omponents omponent public abstract final class NameOflass extends Super Explanation A class can be used only by other classes in the same package; this is the default. The public modifier declares that the class can be used by any class regardless of its package. Declares that the class cannot be instantiated. Declares that the class cannot be subclassed. lass keyword indicates to the compiler that this is a class declaration and that the name of the class is NameOflass. Extends clause identifies Super as the superclass of the class, thereby inserting the class within the class hierarchy. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

5 lass onstructors All Java classes have constructors that are used to initialize a new object of that type. A constructor has the same name as the class. The name of the Stack class's constructor is Stack, the name of the Rectangle class's constructor is Rectangle, and the name of the Thread class's constructor is Thread. Stack defines a single constructor: public Stack() { items = new Vector(0); Java supports name overloading for constructors so that a class can have any number of constructors, all of which have the same name. public Stack(int initialsize) { items = new Vector(initialSize); This is another constructor that could be defined by Stack. This particular constructor sets the initial size of the stack according to its parameter: Both constructors share the same name, Stack, but they have different parameter lists. The compiler differentiates these constructors based on the number of parameters in the list and their types. Typically, a constructor uses its arguments to initialize the new object's state. When creating an object, choose the constructor whose arguments best reflect how to initialize the new object. Based on the number and type of the arguments that you pass into the constructor, the compiler can determine which constructor to use. The compiler knows that when writing the following code, it should use the constructor that requires a single integer argument: new Stack(0); Similarly, when writing the following code, the compiler chooses the no-argument constructor or the default constructor: new Stack(); SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

6 The default constructor is automatically provided by the runtime system for any class that contains no constructors. The default provided by the runtime system doesn't do anything. Therefore, in order to perform some initialization, it will be necessary to write some constructors for the class class AnimationThread extends Thread { int framespersecond; int numimages; Image[] images; AnimationThread(int fps, int num) { super("animationthread"); this.framespersecond = fps; this.numimages = num; this.images = new Image[numImages]; for (int i = 0; i <= numimages; i++) {... // Load all the images The constructor for the subclass of Thread performs animation, sets up some default values, such as the frame speed and the number of images, and then loads the images. The body of a constructor is similar to the body of a method; it contains local variable declarations, loops, and other statements. There is one line in the AnimationThread constructor that wouldn't be part of a method in the second line: super("animationthread"); This line invokes a constructor provided by the superclass of AnimationThread - Thread. This particular Thread constructor takes a String that sets the name of Thread. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

7 Often a constructor will need to take advantage of initialization code written in a class's superclass. Indeed, some classes must call their superclass constructor in order for the object to work properly. If present, the superclass constructor must be the first statement in the subclass's constructor. An object should perform the higher-level initialization first. It is possible to specify what other objects can create instances of a class by using an access specifier in the constructors' declaration. Access Specifier private protected public no specifier gives package access Instance reation by a lass No other class can instantiate the class. The class may contain public class methods (sometimes called factory methods), and those methods can construct an object and return it, but no other classes can. Only subclasses of the class and classes in the same package can create instances of it. Any class can create an instance of your class. Only classes within the same package as your class can construct an instance of it. Only classes within the same package as a class can construct an instance of it. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

8 Member Variable Declaration Stack uses the following line of code to define its single member variable: private Vector items; The member variable declared is named items, and its data type is Vector. The private keyword identifies items as a private member. This means that only code within the Stack class can access it. This will not declare some other type of variable such as a local variable. This is because the declaration appears within the class body, but outside of any methods or constructors. Member variable declarations can be more complex. In addition to type, name, and access level, other attributes can be declared including whether the variable is a class or instance variable and whether it's a constant. omponents of a member variable declaration include: omponent accesslevel static final transient volatile type Explanation ontrols which other classes have access to a member variable by using one of four access levels: public, protected, package, and private. Access to methods is controlled in the same way. Declares that this is a class variable rather than an instance variable. Static is also used to declare class methods. Indicates that the value of this member cannot change. There will be a compile-time error if a program ever tries to change a final variable. By convention, the name of constant values are spelled in uppercase letters. The transient marker is not fully specified by the Java Language Specification. It is used in object serialization to mark member variables that should not be serialized. The volatile keyword is used to prevent the compiler from performing certain optimizations on a member. A member variable must have a type. Primitive type names such as int, float, or boolean can be used. A member variable's name can be any Java identifier; which by convention begins with a lowercase letter. More than one member variable can not be declared with the same name in the same class, but a subclass can hide a member variable of the same name in its superclass. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 6

9 Method Declaration - Details A method's declaration provides information about the method to the compiler, runtime system, and other classes and objects. Included is not only the name of the method, but also such information as the return type of the method, the number and type of the arguments required by the method, and which other classes and objects can call the method. Most method attributes can be declared implicitly. The only required elements of a method declaration are the method's name, its return type, and a pair of parentheses ( ). Elements of a Method Declaration Elements accesslevel static abstract final native synchronized returntype methodname (paramlist) [throws exceptions] Returning a Value from a Method Explanation ontrol of which other classes have access to a method is done using one of four access levels: public, protected, package, and private. Declares this method as a class method rather than an instance method. Has no implementation and must be a member of an abstract class. an not be overridden by subclasses. Methods implemented in a language other than Java are called native methods and are declared using the native keyword. Library of functions written in another language can be used from Java. oncurrently running threads often invoke methods that operate on the same data. These methods can be declared synchronized to ensure that the threads access information in a thread-safe manner. Java requires that a method declare the data type of the value that it returns. If your method does not return a value, use the keyword void for the return type. A method name can be any legal Java identifier. Information can be passed into a method through its arguments. If a method throws any checked exceptions, the method declaration must indicate the type of those exceptions. A method's return type is declared in its method declaration. Within the body of the method, the return operator is used for returning the value. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 7

10 Any method that is not declared void must contain a return statement. The Stack class declares the isempty method, which returns a boolean: 6 public boolean isempty() { if (items.size() == 0) return true; else return false; The data type of the return value must match the method's return type; an Object type can not be returned from a method declared to return an integer. The isempty method returns either the boolean value true or false, depending on the outcome of a test. A compiler error results if a method is written in which the return value doesn't match the return type. The isempty method returns a primitive type. Methods also can return a reference type public synchronized Object pop() { int len = items.size(); Object obj = null; if (len == 0) throw new EmptyStackException(); obj = items.elementat(len - ); items.removeelementat(len - ); return obj; Stack declares the pop method that returns the Object reference type. When a method returns an object such as pop does, the class of the returned object must be either a subclass of or the exact class of the return type. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 8

11 6 Method Body Within an object's method body, the standard approach is to refer directly to the object's member variables. However, sometimes it will be necessary to disambiguate the member variable name if one of the arguments to the method has the same name. 6 7 class HSBolor { int hue, saturation, brightness; HSBolor (int hue, int saturation, int brightness) { this.hue = hue; this.saturation = saturation; this.brightness = brightness; The constructor for the HSBolor class initializes some of an object's member variables according to the arguments passed into the constructor. Each argument to the constructor has the same name as the object's member variable whose initial value the argument contains. The this keyword is used for removing ambiguity regarding the argument and member variables. Argument names take precedence and hide member variables with the same name. In order to refer to the member variable it must be done through the current object explicitly by using the this keyword. Some programmers prefer to use the this keyword when referring to a member variable of the object whose method the reference appears. This will serve to explicitly qualify the intent of the code explicit and reduces error based on name sharing. The this keyword can also be used for calling one of the current object's methods. This will only be necessary if there is some ambiguity in the method name and is often used to make the intent of the code more clear. If a method hides one of its superclass's member variables, it can refer to the hidden variable through the use of the super keyword. Similarly, if a method overrides one of its superclass's methods, another method can invoke the overridden method through the use of the super keyword. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 9

12 lass 6 class ASillylass { boolean avariable; void amethod() { avariable = true; Subclass The sublass hides avariable and overrides amethod class ASillierlass extends ASillylass { boolean avariable; void amethod() { avariable = false; super.amethod(); System.out.println(aVariable); System.out.println(super.aVariable);. amethod sets avariable; this is variable which has been declared in ASillierlass that hides the one declared in ASillylass to false.. amethod invokes its overridden method with this statement: super.amethod(); SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 0

13 7 Local Variables Within the body of the method, it is possible to declare more variables for use within that method. Variables of this type are local variables and live only while control remains within the method Object findobjectinarray(object o, Object[] arrayofobjects) { int i; // local variable for (i = 0; i < arrayofobjects.length; i++) { if (arrayofobjects[i] == o) return o; return null; This method declares a local variable i that it uses to iterate over the elements of its array argument. After this method returns, i no longer exists. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

14 8 Inheritance - Managing The extends clause declares that a class is a subclass of another. Java does not support multiple class inheritance. Only one class can be specified for a superclass for a class. Even though the extends clause can be omitted from a class declaration, the class will still have a superclass. A subclass is a class that extends another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a class's direct ancestor as well as to all of its ascendant classes. A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these members as is, or it can hide the member variables or override the methods. A subclass inherits all of the members in its superclass that are accessible to that subclass unless the subclass explicitly hides a member variable or overrides a method. onstructors are not members and are not inherited by subclasses. The following rules apply to inheritance by a subclass: 8. Members Inherited by a Subclass Subclasses inherit those superclass members declared as public or protected. Subclasses inherit those superclass members declared with no access specifier as long as the subclass is in the same package as the superclass. Subclasses don't inherit a superclass's member if the subclass declares a member with the same name. - In the case of member variables, the member variable in the subclass hides the one in the superclass. - In the case of methods, the method in the subclass overrides the one in the superclass. reating a subclass can be performed by including the extends clause in a class declaration. However, other provisions will have to be made in the code when subclassing a class. Typically this will be overriding methods or providing implementations for abstract methods. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

15 9 Member Variables - Hiding Member variables defined in the subclass, hide member variables that have the same name in the superclass. Although extremely useful, it can be a source of errors. When naming member variables, care needs to be taken in order to hide only those member variables that are intended to be hidden. A feature of Java member variables is that a class can access a hidden member variable through its superclass. 6 class Super { Number anumber; class Subbie extends Super { Float anumber; The anumber variable in Subbie hides anumber in Super. Super's anumber can be accessed from Subbie with super.anumber. super is a Java language keyword that allows a method to refer to hidden variables and overridden methods of the superclass. The ability of a subclass to override a method in its superclass allows a class to inherit from a superclass whose behavior is "close enough" and then supplement or modify the behavior of that superclass. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

16 0 Overriding Methods The ability of a subclass to override a method in its superclass allows a class to inherit from a superclass whose behavior is "close enough" and then override methods as needed. All classes are descendants of the Object class. Object contains the tostring method, which returns a String object containing the name of the object's class and its hash code. Most, if not all, classes will want to override this method and print out something meaningful for that class. The return type, method name, and number and type of the parameters for the overriding method must match those in the overridden method. The overriding method can have a different throws clause as long as it doesn't declare any types not declared by the throws clause in the overridden method. The access specifier for the overriding method can allow more access than the overridden method, but not less. A protected method in the superclass can be made public, but not private. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

17 Overridden Method - alling There will be times when there will be a requirement not to completely override a method. Additional functionality can be added by calling the overridden method using the super keyword. super.overriddenmethodname();. Methods a Subclass annot Override A subclass cannot override methods that are declared final in the superclass. If there is an attempt to override a final method, the compiler displays an error message similar to the following and refuses to compile the program: FinalTest.java:7: Final methods can't be overridden. Method void iamfinal() is final in class lasswithfinalmethod. void iamfinal() { ^ error A subclass cannot override methods that are declared static in the superclass. A subclass cannot override a class method. A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass.. Methods a Subclass Must Override A subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

18 Object Descendent The object class sits at the top of the class hierarchy tree in the Java platform. Every class in the Java system is a descendent, direct or indirect, of the Object class. This class defines the basic state and behavior that all objects must have, such as the: ability to compare oneself to another object. convert to a string. wait on a condition variable. notify other objects that a condition variable has changed. return the class of the object. There are times when a class will want to override the following Object methods: clone equals/hashode finalize tostring The equals/hashode are listed together as they must be overridden together. A class cannot override these Object methods: getlass notify notifyall wait SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 6

19 clone Method The clone method is used for creating an object from an existing object. To create a clone: aloneableobject.clone(); An object's implementation of this method checks to see if the object on which clone was invoked implements the loneable interface, and throws a lonenotsupportedexception if it does not. The Object itself does not implement loneable, so subclasses of Object that don't explicitly implement the interface are not cloneable. If the object on which clone was invoked does implement the loneable interface, Object's implementation of the clone method creates an object of the same type as the original object and initializes the new object's member variables to have the same values as the original object's corresponding member variables. A simple way to make a class cloneable then, is to add implements loneable to a class's declaration. For some classes the default behavior of Object's clone method will work just fine. Other classes need to override clone to get correct behavior public class Stack implements loneable { private Vector items; // code for Stack's methods and constructor not shown protected Object clone() { try { Stack s = (Stack)super.clone(); // clone the stack s.items = (Vector)items.clone(); // clone the vector return s; // return the clone catch (lonenotsupportedexception e) { // this shouldn't happen because Stack is loneable throw new InternalError(); The Stack class contains a member variable that refers to a Vector. If Stack relies on Object's implementation of clone, then the original stack and its clone will refer to the same vector. hanging one stack will result in a change in an other. This is not a desirable behavior. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 7

20 The implementation for Stack's clone method is straightforward; it calls super.clone, which Stack inherits from Object and which creates and initializes an instance of the correct type. The original stack and its clone now refer to the same vector. The method then clones the vector. lone should never use new to create the clone and should not call constructors. Rather, the method should call super.clone, which creates an object of the correct type and allows the hierarchy of superclasses to perform the copying necessary to get a proper clone. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 8

21 The equals and hashode methods must be overridden together. The equals and hashode Methods The equals method compares two objects for equality and returns true if they are equal. The equals method provided in the Object class uses the identity function to determine whether objects are equal. When the objects being compared are the exact same object the method returns true. However, for some classes, two distinct objects of that type might be considered equal if they contain the same information. This code tests two Integers, one and anotherone, for equality. Integer one = new Integer(), anotherone = new Integer(); if (one.equals(anotherone)) System.out.println("objects are equal"); This program displays objects are equal even though one and anotherone reference two distinct objects. They are considered equal because the objects compared contain the same integer value. lasses should only override the equals method if the identity function is not appropriate for a class. If equals is overriden, then override hashode as well. The value returned by hashode is an int that maps an object into a bucket in a hash table. An object must always produce the same hash code. However, objects can share hash codes. Writing a hashing function is easy; always return the same hash code for the same object. Writing an efficient hashing function, one that provides a sufficient distribution of objects over the buckets, is difficult. Even so, the hashing function for some classes is straightforward. A hash code for an Integer object is its integer value. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 9

22 Final lasses and Methods - Writing lasses can be declared as final; this means that a class cannot be subclassed. The reasons for doing this would be: increasing system security by preventing system subversion. sound object-oriented design.. Security One mechanism that hackers use to subvert systems is to create a subclass of a class and then substitute their class for the original. The subclass looks like the original class; but does different things, possibly causing damage or getting into private information. To prevent this from occurring, a class can be declared as final and thereby prevent any subclasses from being created. The String class in the java.lang package is a final class for just this reason. This class is vital to the operation of the compiler and the interpreter must guarantee that whenever a method or object uses a String it gets exactly a java.lang.string and not some other string. This will ensure that all strings have no inconsistent, undesirable, or unpredictable properties.. Design A class can be designed as final for object-oriented design reasons. To specify that a class is final, use the keyword final before the class keyword in the class declaration. final class hessalgorithm {... This declaration will declare (perfect) hessalgorithm class as final. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 0

23 6 Final Methods The final keyword can be used in a method declaration to indicate to the compiler that the method cannot be overridden by subclasses. The Object class does this; some of its methods are final and some are not. It might be necessary to make a method final if it has an implementation that should not be changed and which is critical to the consistent state of the object. This code will serve to make the nextmove method final; instead of Algorithm class final class hessalgorithm {... final void nextmove(hesspiece piecemoved, BoardLocation newlocation) { SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

24 7 Abstract lasses and Methods - Writing Sometimes there will be classes that have been defined which represent an abstract concept; these classes should not be instantiated. In object-oriented programming, there will be models for abstract concepts which will not be able to create an instance of it. For example, the Number class in the java.lang package represents the abstract concept of numbers. It makes sense to model numbers in a program, but it doesn't make sense to create a generic number object. Instead, the Number class makes sense only as a superclass to classes like Integer and Float, both of which implement specific kinds of numbers. A class such as Number, which represents an abstract concept and should not be instantiated, is called an abstract class. An abstract class is a class that can only be subclassed - it cannot be instantiated. To declare a class is an abstract class, use the keyword abstract before the class keyword in the class declaration: abstract class Number {... When an attempt is made to instantiate an abstract class, the compiler displays an error. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

25 8 Abstract Methods An abstract class may contain abstract methods; abstract methods are classes which have no implementation. An abstract class can define a complete programming interface, thereby providing its subclasses with the method declarations for all of the methods necessary to implement that programming interface. The abstract class can leave some or all of the implementation details of those methods up to its subclasses. 8. Abstract lass with an Abstract Method An object-oriented drawing application can be used for drawing circles, rectangles, lines, Bezier curves, and so on. Each of these graphic objects share certain states such as position, bounding box and behavior such as move, resize, and draw. An efficient use of these similarities would be to declare and inherit them from the same parent object - GraphicObject. In addition to the similarities, these graphic objects also have substantial differences; for example drawing a circle is quite different from drawing a rectangle. The graphics objects cannot share these types of states or behavior. On the other hand, all GraphicObjects must know how to draw themselves; they differ in how they are drawn. This is a situation which lends itself to the creation of an abstract superclass. The steps for implementing a superclass would be:. Declare an abstract class, GraphicObject, to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveto method.. GraphicObject is to declare abstract methods for methods, such as draw, which will need to be implemented by all subclasses, but be implemented in entirely different ways. Having no default implementation in the superclass is reasonable. The GraphicObject class would be as follows: abstract class GraphicObject { int x, y;... void moveto(int newx, int newy) {... abstract void draw(); SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

26 Each non-abstract subclass of GraphicObject, such as ircle and Rectangle, would have to provide an implementation for the draw method class ircle extends GraphicObject { void draw() {... class Rectangle extends GraphicObject { void draw() {... SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

27 9 Interface An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. It defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. An interface is a named collection of method definitions without implementations. An interface can also declare constants. Since an interface is a list of unimplemented abstract methods, a fundamental question is how an interface differs from an abstract class. The differences are: An interface cannot implement any methods, whereas an abstract class can. A class can implement many interfaces but can have only one superclass. An interface is not part of the class hierarchy; unrelated classes can implement the same interface. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

28 9. Interface Example Functional Specification A class needs to be defined for watching stock prices coming over a data feed. This class will allow other classes to register to be notified when the value of a particular stock changes. The StockMonitor class would implement a method that lets other objects register for notification. ode 6 public class StockMonitor { public void watchstock(stockwatcher watcher, String tickersymbol, double delta) {... The first argument to this method is a StockWatcher object. StockWatcher is the name of an interface. That interface declares one method: valuehanged. An object that wants to be notified of stock changes must be an instance of a class that implements this interface and thus implements the valuehanged method. The other two arguments provide the symbol of the stock to watch and the amount of change that the watcher considers interesting enough to be notified of. When the StockMonitor class detects an interesting change, it calls the valuehanged method of the watcher. The watchstock method ensures, through the data type of its first argument, that all registered objects implement the valuehanged method. It makes sense to use an interface data type because it matters only that registrants implement a particular method. An interface definition has two components: 9. Interface Definition interface declaration interface body The interface declaration declares various attributes about the interface, such as its name and whether it extends other interfaces. The interface body contains the constant and the method declarations for that interface. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 6

29 The StockWatcher interface and the structure of an interface definition would be implemented as: 6 7 public interface StockWatcher { final String sunticker = "SUNW"; final String oracleticker = "ORL"; final String ciscoticker = "SO"; void valuehanged(string tickersymbol, double newvalue); This interface defines three constants, which are the ticker symbols of watchable stocks. This interface also declares, but does not implement, the valuehanged method. lasses that implement this interface provide the implementation for that method. Two elements are required in an interface declaration: interface keyword name of the interface The public access specifier indicates that the interface can be used by any class in any package. If an interface is not specified as public, the interface will be accessible only to classes that are defined in the same package as the interface. An interface declaration can have one other component; a list of superinterfaces. An interface can extend other interfaces, such as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The list of superinterfaces is a comma-separated list of all the interfaces extended by the new interface. The interface body contains method declarations for all the methods included in the interface. A method declaration within an interface is followed by a semicolon (;) because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly public and abstract. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 7

30 9. Interface Implementation An interface defines a protocol of behavior. A class that implements an interface adheres to the protocol defined by that interface. To declare a class that implements an interface, include an implements clause in the class declaration. A class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class public class StockApplet extends Applet implements StockWatcher {... public void valuehanged(string tickersymbol, double newvalue) { if (tickersymbol.equals(sunticker)) {... else if (tickersymbol.equals(oracleticker)) {... else if (tickersymbol.equals(ciscoticker)) {... An applet which implements the StockWatcher interface. This class refers to each constant defined in StockWatcher,sunTicker, oracle-ticker, imple name. lasses that implement an interface inherit the constants defined within that interface. So those classes can use simple names to refer to the constants. Any other class can use an interfaces constants with a qualified name: StockWatcher.sunTicker SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 8

31 0 Packages To make classes easier to find and use, avoid naming conflicts, and control access, programmers bundle groups of related classes and interfaces into packages. A package is a collection of related classes and interfaces providing access protection and namespace management. The classes and interfaces that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang. classes for reading and writing (input and output) are in java.io lasses and interfaces can be placed in packages. 0. lasses - Placing in a Package onsider a group of classes which has been written to represent a collection of graphic objects, such as circles, rectangles, lines, and points. An interface can be written, Draggable, that classes implement if they have the capability of being dragged with the mouse by the user: //in the Graphic.java file public abstract class Graphic {... //in the ircle.java file public class ircle extends Graphic implements Draggable {... //in the Rectangle.java file public class Rectangle extends Graphic implements Draggable {... //in the Draggable.java file public interface Draggable {... SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 9

32 These classes should be bundled and the interface placed in a package for several reasons: It will be easier to determine that these classes and interfaces are related. Programmers will know where to find classes and interfaces that provide graphics-related functions. Names of classes won t conflict with class names in other packages, because the package creates a new namespace. lasses within the package can be allowed to have unrestricted access to one another; yet still restrict access for classes outside the package. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page 0

33 0. Package reation A package is created by putting a class or an interface in it. This is done by placing a package statement at the top of the source file in which the class or the interface is defined. package graphics; public class ircle extends Graphic implements Draggable {... This code appears in the source file ircle.java and puts the ircle class in the graphics package. The ircle class is a public member of the graphics package. A package statement must be included at the top of every source file that defines a class or an interface that is to be a member of the graphics package. The following statement would be included in Rectangle.java: package graphics; public class Rectangle extends Graphic implements Draggable {... The scope of the package statement is the entire source file, so all classes and interfaces defined in ircle.java and Rectangle.java are also members of the graphics package. If multiple classes are placed in a single source file, only one may be public, and it must share the name of the source files base name. Only public package members are accessible from outside the package. If a package statement is not used, the class or interface ends up in the default package, which is a package that has no name. In general, the default package is only for small or temporary applications or when the development is just beginning. Otherwise, classes and interfaces belong in named packages. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

34 0. Package Naming With programmers writing classes and interfaces using the Java programming language, there is a high likelihood that two programmers will use the same name for two different classes. ompanies use their reversed Internet domain name in their package names: com.company.package Some companies elect to drop the first element com. Name collisions that occur within a single company need to be handled by convention within that company. One approach for doing this would be to include the region or the project name after the company name e.g. com.company.region.package. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

35 0. Package Members Only public package members are accessible outside the package in which they are defined. To use a public package member from outside its package, one or more of the following steps must be taken: Refer to the member by its long (qualified) name. Import the package member. Import the members entire package. Each is appropriate for different situations. A package members simple name can be used when the code that is being written is in the same package as that member or if the members package has been imported. However, if a member from a different package is to be used and that package has not been imported, the members qualified name must be used; this name will include the package name. This qualified name for the Rectangle class declared in the graphics package example would be: graphics.rectangle This long name could be used for creating an instance of graphics.rectangle: graphics.rectangle myrect = new graphics.rectangle(); The use of long names will be satisfactory for a single use. However, it would quickly become annoying if graphics.rectangle had to be written again and again. The code would become very messy and difficult to read. In such cases, the member would need to be imported instead. To import a specific member into the current file, put an import statement at the beginning of the file before any class or interface definitions but after the package statement. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

36 import graphics.ircle; ircle class can now be referred to by its simple name: ircle myircle = new ircle(); This approach works well when only a few members from the graphics package are being used. If many classes and interfaces from a package are being used, then the entire package can be imported. To import all the classes and interfaces contained in a particular package, use the import statement with the asterisk (*) wildcard character: import graphics.*; Any class or interface in the graphics package can now be referred to by its short name: ircle myircle = new ircle(); Rectangle myrectangle = new Rectangle(); The asterisk in the import statement can be used only to specify all the classes within a package. It cannot be used to match a subset of the classes in a package. import graphics.a*; // does not work The code does not match all the classes in the graphics package that begin with A. SYS-ED \OMPUTER EDUATION TEHNIQUES, IN. (JAVA PRG - ADV -.) h : Page

Subclasses, Superclasses, and Inheritance

Subclasses, Superclasses, and Inheritance Subclasses, Superclasses, and Inheritance To recap what you've seen before, classes can be derived from other classes. The derived class (the class that is derived from another class) is called a subclass.

More information

UCLA PIC 20A Java Programming

UCLA PIC 20A Java Programming UCLA PIC 20A Java Programming Instructor: Ivo Dinov, Asst. Prof. In Statistics, Neurology and Program in Computing Teaching Assistant: Yon Seo Kim, PIC Chapter 5 Classes & Inheritance Creating Classes

More information

Inheritance. The Java Platform Class Hierarchy

Inheritance. The Java Platform Class Hierarchy Inheritance In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Course 4 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Inheritance A class that is derived from another class is called a subclass (also a derived class, extended class,

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

S.E. Sem. III [CMPN] Object Oriented Programming Methodology S.E. Sem. III [CMPN] Object Oriented Programming Methodology Time : 3 Hrs.] Prelim Question Paper Solution [Marks : 80 Q.1(a) Write a program to calculate GCD of two numbers in java. [5] (A) import java.util.*;

More information

More on Objects in JAVA TM

More on Objects in JAVA TM More on Objects in JAVA TM Inheritance : Definition: A subclass is a class that extends another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 22. Inheritance Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Inheritance Object-oriented programming

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini 24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Casting -Allows a narrowing assignment by asking the Java compiler to trust us Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Java Threads and intrinsic locks

Java Threads and intrinsic locks Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson ) (SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson ) Dongwon Jeong djeong@kunsan.ac.kr; http://ist.kunsan.ac.kr/ Information Sciences and Technology Laboratory, Dept. of

More information

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Points To Remember for SCJP

Points To Remember for SCJP Points To Remember for SCJP www.techfaq360.com The datatype in a switch statement must be convertible to int, i.e., only byte, short, char and int can be used in a switch statement, and the range of the

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Definition of DJ (Diminished Java)

Definition of DJ (Diminished Java) Definition of DJ (Diminished Java) version 0.5 Jay Ligatti 1 Introduction DJ is a small programming language similar to Java. DJ has been designed to try to satisfy two opposing goals: 1. DJ is a complete

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

CSCE3193: Programming Paradigms

CSCE3193: Programming Paradigms CSCE3193: Programming Paradigms Nilanjan Banerjee University of Arkansas Fayetteville, AR nilanb@uark.edu http://www.csce.uark.edu/~nilanb/3193/s10/ Programming Paradigms 1 Java Packages Application programmer

More information

Chapter 4 Java Language Fundamentals

Chapter 4 Java Language Fundamentals Chapter 4 Java Language Fundamentals Develop code that declares classes, interfaces, and enums, and includes the appropriate use of package and import statements Explain the effect of modifiers Given an

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract

More information

OVERRIDING. 7/11/2015 Budditha Hettige 82

OVERRIDING. 7/11/2015 Budditha Hettige 82 OVERRIDING 7/11/2015 (budditha@yahoo.com) 82 What is Overriding Is a language feature Allows a subclass or child class to provide a specific implementation of a method that is already provided by one of

More information

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC. hapter 1 INTRODUTION SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Objectives You will learn: Java features. Java and its associated components. Features of a Java application and applet. Java data types. Java

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Chapter 11 Classes Continued

Chapter 11 Classes Continued Chapter 11 Classes Continued The real power of object-oriented programming comes from its capacity to reduce code and to distribute responsibilities for such things as error handling in a software system.

More information

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC. hapter 1 INTRODUTION SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. ++ Programming: Advanced Objectives You will learn: Anonymous class types. Nested class declarations. Incomplete declarations. Pointers to class

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM 1 of 18 9/6/2010 9:40 PM Flash CS4 Professional ActionScript 3.0 Language Reference Language Reference only Compiler Errors Home All Packages All Classes Language Elements Index Appendixes Conventions

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Logistics. Final Exam on Friday at 3pm in CHEM 102

Logistics. Final Exam on Friday at 3pm in CHEM 102 Java Review Logistics Final Exam on Friday at 3pm in CHEM 102 What is a class? A class is primarily a description of objects, or instances, of that class A class contains one or more constructors to create

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 7 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

Building Java Programs. Inheritance and Polymorphism

Building Java Programs. Inheritance and Polymorphism Building Java Programs Inheritance and Polymorphism Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

Self-review Questions

Self-review Questions 7Class Relationships 106 Chapter 7: Class Relationships Self-review Questions 7.1 How is association between classes implemented? An association between two classes is realized as a link between instance

More information

Packages. Examples of package names: points java.lang com.sun.security drawing.figures

Packages. Examples of package names: points java.lang com.sun.security drawing.figures Packages To make classes easier to find and to use, to avoid naming conflicts, and to control access, programmers bundle groups of related classes and interfaces into packages. A package is a program module

More information

5.6.1 The Special Variable this

5.6.1 The Special Variable this ALTHOUGH THE BASIC IDEAS of object-oriented programming are reasonably simple and clear, they are subtle, and they take time to get used to And unfortunately, beyond the basic ideas there are a lot of

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

1/16/2013. Program Structure. Language Basics. Selection/Iteration Statements. Useful Java Classes. Text/File Input and Output.

1/16/2013. Program Structure. Language Basics. Selection/Iteration Statements. Useful Java Classes. Text/File Input and Output. Program Structure Language Basics Selection/Iteration Statements Useful Java Classes Text/File Input and Output Java Exceptions Program Structure 1 Packages Provide a mechanism for grouping related classes

More information

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 10 Inheritance Chapter Topics (1 of 2) 10.1 What Is Inheritance? 10.2 Calling the Superclass Constructor 10.3 Overriding

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. Preface p. xix Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. 5 Java Applets and Applications p. 5

More information

7. C++ Class and Object

7. C++ Class and Object 7. C++ Class and Object 7.1 Class: The classes are the most important feature of C++ that leads to Object Oriented programming. Class is a user defined data type, which holds its own data members and member

More information

F I N A L E X A M I N A T I O N

F I N A L E X A M I N A T I O N Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student

More information

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation CSE 452: Programming Languages Data Abstraction and Object-Orientation Previous Lecture Abstraction Abstraction is the elimination of the irrelevant and the amplification of the essential Robert C Martin

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Developed in the beginning of the 1990 s by James Gosling from Sun Microsystems. Formally announced in a major conference in 1995.

Developed in the beginning of the 1990 s by James Gosling from Sun Microsystems. Formally announced in a major conference in 1995. JAVA Developed in the beginning of the 1990 s by James Gosling from Sun Microsystems. Formally announced in a major conference in 1995. Java programs are translated (compiled) into Byte Code format. The

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems Basics of OO Programming with Java/C# Basic Principles of OO Abstraction Encapsulation Modularity Breaking up something into smaller, more manageable pieces Hierarchy Refining through levels of abstraction

More information

The Java Programming Language

The Java Programming Language The Java Programming Language Slide by John Mitchell (http://www.stanford.edu/class/cs242/slides/) Outline Language Overview History and design goals Classes and Inheritance Object features Encapsulation

More information

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides 1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of

More information

Polymorphism and Interfaces. CGS 3416 Spring 2018

Polymorphism and Interfaces. CGS 3416 Spring 2018 Polymorphism and Interfaces CGS 3416 Spring 2018 Polymorphism and Dynamic Binding If a piece of code is designed to work with an object of type X, it will also work with an object of a class type that

More information

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 10 Classes Continued. Fundamentals of Java Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an

More information

Polymorphism and Inheritance

Polymorphism and Inheritance Walter Savitch Frank M. Carrano Polymorphism and Inheritance Chapter 8 Objectives Describe polymorphism and inheritance in general Define interfaces to specify methods Describe dynamic binding Define and

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

More information

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass? COMP9024: Data Structures and Algorithms Week One: Java Programming Language (II) Hui Wu Session 1, 2014 http://www.cse.unsw.edu.au/~cs9024 Outline Inheritance and Polymorphism Interfaces and Abstract

More information