Lesson 3.3: Object-Oriented Programming Flashcards

1
Q

In Java، what are packages and what are interfaces?

A

Packages are groups of related classes. Packages help organize your code and provide another layer of encapsulation. As you will see in Chapter 15، packages also play an important role with modules. An interface defines a set of methods that will be implemented by a class. Thus، an interface gives you a way to specify what a class will do، but not how it will do it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the two main purposes of packages?

A

First، it provides a mechanism by which related pieces of a program can be organized as a unit. Classes defined within a package must be accessed through their package name. Thus، a package provides a way to name a collection of classes. Second، a package participates in Java’s access control mechanism. Classes defined within a package can be made private to that package and not accessible by code outside the package. Thus، the package provides a means by which classes can be encapsulated

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are namespaces in Java?

A

In general، when you name a class، you are allocating a name from the namespace. A namespace defines a declarative region. In Java، no two classes can use the same name from the same namespace. Thus، within a given namespace، each class name must be unique.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What happens to a class if you don’t assign it a package?

A

All classes in Java belong to some package. When no package statement is specified، the default package is used. Furthermore، the default package has no name، which makes the default package transparent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you create a package and what is its general form?

A

To create a package، put a package command at the top of a Java source file. The classes declared within that file will then belong to the specified package. Since a package defines a namespace، the names of the classes that you put into the file become part of that package’s namespace. This is the general form of the package statement: package pkg; Here، pkg is the name of the package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

If you define a class as part of a package، can you use other packages in that class?

A

The package statement simply specifies to which package the classes defined in a file belong. It does not exclude other classes in other files from being part of that same package. Most real-world packages are spread across many files.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you create packages inside other packages?

A

You can create a hierarchy of packages. To do so، simply separate each package name from the one above it by use of a period. The general form of a multileveled package statement is shown here: package pack1.pack2.pack3…packN; Page 276Of course، you must create directories that support the package hierarchy that you create.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How does the Java run-time system know where to look for packages that you create?

A

the answer has three parts. First، by default، the Java run-time system uses the current working directory as its starting point. Thus، if your package is in a subdirectory of the current directory، it will be found. Second، you can specify a directory path or paths by setting the CLASSPATH environmental variable. Third، you can use the -classpath option with java and javac to specify the path to your classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Where should you keep a java and class file? Where should it be compiled from?

A

To avoid problems، it is best to keep all .java and .class files associated with a package in that package’s directory. Also، compile each file from the directory above the package directory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What happens when a member of a class with package membership doesn’t have an explicit modifier?

A

If a member of a class has no explicit access modifier، then it is visible within its package but not outside its package. Therefore، you will use the default access specification for elements that you want to keep private to a package but public within that package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does it mean to declare a member of a class with membership in a package when declared public or private?

A

Members explicitly declared public are the most visible، and can be accessed from different classes and different packages. A private member is accessible only to the other members of its class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

When a member of a package is declared as protected، what is its accessibility?

A

A member specified as protected is accessible within its package and to subclasses in other packages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What type of members have access to the protected modifier?

A

the protected modifier creates a member that is accessible within its package and to subclasses in other packages. Thus، a protected member is available for all subclasses to use but is still protected from arbitrary access by code outside its package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does the import statement mean and what is it’s general form?

A

Using import you can bring one or more members of a package into view. This allows you to use those members directly، without explicit package qualification. Page 283Here is the general form of the import statement: import pkg.classname; Here، pkg is the name of the package، which can include its full path، and classname is the name of the class being imported. If you want to import the entire contents of a package، use an asterisk (*) for the class name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Where do you put import statement in a code?

A

In a Java source file، import statements occur immediately following the package statement (if it exists) and before any class definitions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the Java API?

A

Java defines a large number of standard classes that are available to all programs. This class library is often referred to as the Java API (Application Programming Interface). The Java API is stored in packages. At the top of the package hierarchy is java. Descending from java are several subpackages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Why is the java.lang subpackage unique?

A

java.lang. It contains، among several others، the System class، which you have been using when performing output using println( ). The java.lang package is unique because it is imported automatically into every Java program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is an interface in Java?

A

An interface is syntactically similar to an abstract class، in that you can specify one or more methods that have no body. Those methods must be implemented by a class in order for their actions to be defined. Thus، an interface specifies what must be done، but not how to do it. Once an interface is defined، any number of classes can implement it. Also، one class can implement any number of interfaces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the general form of a traditional interface?

A

Here is a simplified general form of a traditional interface: access interface name { ret-type method-name1(param-list); ret-type method-name2(param-list); type var1 = value; type var2 = value; // … ret-type method-nameN(param-list); type varN = value; } For a top-level interface، access is either public or not used. When no access modifier is included، then default access results، and the interface is available only to other members of its package. When it is declared as public، the interface can be used by any other code. (When an interface is declared public، it must be in a file of the same name.) name is the name of the interface and can be any valid identifier، except for var (which is a reserved type name added by JDK 10).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the form of a class that includes the implements clause? What if you want to implement more that one interface?

A

The general form of a class that includes the implements clause looks like this: class classname extends superclass implements interface { // class-body } Page 286To implement more than one interface، the interfaces are separated with a comma. Of course، the extends clause is optional.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

When is a class considered “abstract”? Why are they benificial?

A

If a class includes an interface but does not fully implement the methods defined by that interface، then that class must be declared abstract. No objects of such a class can be created، but it can be used as an abstract superclass، allowing subclasses to provide the complete implementation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

***TT 8-1

A

“1. Create a file called ICharQ.java and put into that file the following interface definition: // A character queue interface. public interface ICharQ { //Put a character into the queue. void put(char ch); //Get a character from the queue. char get(); } As you can see، this interface is very simple، consisting of only two methods. Each class that implements ICharQ will need to implement these methods. 2. Create a file called IQDemo.java. 3. Begin creating IQDemo.java by adding the FixedQueue class shown here: //A fixed-size queue class for characters. class FixedQueue implements ICharQ { private char q[]; //This array holds the queue. private int putloc، getloc; //The put and get indices //Construct an empty queue given its size. public FixedQueue(int size) { q = new char[size]; //Allocate memory for queue. putloc = getloc = 0; } //Put a character into the queue. public void put(char ch) { if(putloc == q.length) { System.out.println(“ Queue is full.”); return; } q[putloc++] = ch; } //Get a character from the queue. public char get() { if(getloc == putloc) { System.out.println(“ Queue is empty.”); return (char) 0; } return q[getloc++]; } } This implementation of ICharQ is adapted from the Queue class shown in Chapter 5 and should already be familiar to you. 4. To IQDemo.java add the CircularQueue class shown here. It implements a circular queue for characters. //A circular queue. class CircularQueue implements ICharQ { private char q[]; //This array holds the queue. private int putloc، getloc; //The put and get indices //Construct an empty queue given its size. public CircularQueue(int size) { q = new char[size + 1]; //Allocate memory for queue. putloc = getloc = 0; } //Put a character into the queue. public void put(char ch) { /Queue is full if either putloc is one less than getloc or if putloc is at the end of the array and getloc is at the beginning./ if(putloc + 1 == getloc | ((putloc == q.length 1) & (getloc == 0))) { System.out.println(“ Queue is full.”); return; } q[putloc++] = ch; if(putloc == q.length) putloc = 0; //Loop back. } //Get a character from the queue. public char get() { if(getloc == putloc) { System.out.println(“ Queue is empty.”); return (char) 0; } char ch = q[getloc++]; if(getloc == q.length) getloc = 0; //Loop back. return ch; } } The circular queue works by reusing space in the array that is freed when elements are retrieved. Thus، it can store an unlimited number of elements as long as elements are also being removed. While conceptually simple—just reset the appropriate index to zero when the end of the array is reached—the boundary conditions are a bit confusing at first. In a circular queue، the queue is full not when the end of the underlying array is reached، but rather when storing an item would cause an unretrieved item to be overwritten. Thus، put( ) must check several conditions in order to determine if the queue is full. As the comments suggest، the queue is full when either putloc is one less than getloc، or if putloc is at the end of the array and getloc is at the beginning. As before، the queue is empty when getloc and putloc are equal. To make these checks easier، the underlying array is created one size larger than the queue size. 5. Put into IQDemo.java the DynQueue class shown next. It implements a “growable” queue that expands its size when space is exhausted. // A dynamic queue. class DynQueue implements ICharQ { private char q[]; // This array holds the queue private int putloc، getloc; // The put and get indices // Construct an empty queue given its size. public DynQueue(int size) { q = new char[size]; // Allocate memory for queue putloc = getloc = 0; } // Put a character into the queue. public void put(char ch) { if (putloc==q.length) { // Increase queue size char t[] = new char[q.length * 2]; // Copy elements into new queue for(int i=0; i < q.length; i++){ t[i] = q[i]; } q = t; } q[putloc++] = ch; } // Get a character from the queue. public char get(){ if(getloc == putloc){ System.out.println(“ Queue is empty.”); } return (char) 0; } } In this queue implementation، when the queue is full، an attempt to store another element causes a new underlying array to be allocated that is twice as large as the original، the current contents of the queue are copied into this array، and a reference to the new array is stored in q. 6. To demonstrate the three ICharQ implementations، enter the following class into IQDemo.java. It uses an ICharQ reference to access all three queues. // Demonstrate the ICharQ interface. class IQDemo { public static void main(String args[]) { FixedQueue q1 = new FixedQueue (10); DynQueue q2 = new DynQueue (5); CircularQueue q3 = new CircularQueue (10); ICharQ iQ: char ch; int i; iQ = q1; // Put some characters into fixed queue. for (i=0; i < 10; i++){ iQ.put((char) (‘A’ + i)); } // Show the queue. System.out.println(“Contents of fixed queue: “); for(i=0; i<10; i++) { ch = iQ.get(); System.out.print(ch); } System.out.println(); iQ = q2; // Put some characters into dynamic queue. for(i=0; i<10; i++){ iQ.put((char) (‘Z’ 1)); // Show the queue. System.out.print(“Contents of dynamic queue: “); for(i=0; i<10; i++) { ch iQ.get(); System.out.print(ch); } System.out.println(); iQ = q3; // Put some characters into circular queue. for(i=0; i<10; i++) { iQ.put((char) (‘A’ + i)); // Show the queue. System.out.print(“Contents of circular queue: “); for(i=0; i<10; i++) { ch iQ.get(); System.out.print (ch); } System.out.println(); // Put more characters into circular queue. for(i=10; i < 20; 1++) { iQ.put((char) (‘A’ + i)); } // Show the queue . System.out.print(“Contents of circular queue: “); for(i=0; i < 10; i++) { ch = iQ.get(); System.out.print (ch); } System.out.println(“\nStore and consume from” + “ circular queue.”); // Store in and consume from circular queue. for(i=0; i< 20; i++) { iQ.put((char) (‘A’ + i)); ch = iQ.get(); System.out.print (ch); } } } 7. The output from this program is shown here: Contents of fixed queue: ABCDEFGHIJ Contents of dynamic queue: ZYXWVUTSRQ Contents of circular queue: ABCDEFGHIJ Contents of circular queue: KLMNOPQRST Store and consume from circular queue. ABCDEFGHIJKLMNOPQRST 8. Here are some things to try on your own. Create a circular version of DynQueue. Add a reset( ) method to ICharQ، which resets the queue. Create a static method that copies the contents of one type of queue into another.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you define a default method? Provide a coding example for this

A

An interface default method is defined similar to the way a method is defined by a class. The primary difference is that the declaration is preceded by the keyword default. Coding example to the right >

24
Q

What is a default method in an interface، what Java version was it introduced in، and what is its other name?

A

The release of JDK 8 changed this by adding a new capability to interface called the default method. A default method lets you define a default implementation for an interface method. In other words، by use of a default method، it is possible for an interface method to provide a body، rather than being abstract. During its development، the default method was also referred to as an extension method، and you will likely see both terms used.

25
Q

Why doesn’t a default method break a widely used interface anymore? Why did it break in the first place?

A

In the past، if a new method were added to a popular، widely used interface، then the addition of that method would break existing code because no implementation would be found for that method. The default method solves this problem by supplying an implementation that will be used if no other implementation is explicitly provided. Thus، the addition of a default method will not cause preexisting code to break.

26
Q

Give me a code example of a static method in an interface.

A

The following shows an example of a static method in an interface by adding one to MyIF، shown earlier. The static method is getUniversalID( ). It returns zero. Code to the right >

27
Q

What are the two major benefits of default methods?

A

It gives you a way to gracefully evolve interfaces over time without breaking existing code. It provides optional functionality without requiring that a class provide a placeholder implementation when that functionality is not needed.

28
Q

Can you inherit multiple classes using interfaces?

A

Java does not support the multiple inheritance of classes. Now that an interface can include default methods، you might be wondering if an interface can provide a way around this restriction. The answer is، essentially، no. Recall that there is still a key difference between a class and an interface: a class can maintain state information (through the use of instance variables)، but an interface cannot.

29
Q

What set of rules does java define that prevent interfaces from name syntax errors when interacting with each other?

A

First، in all cases a class implementation takes priority over an interface default implementation. Second، in cases in which a class inherits two interfaces that both have the same default method، if the class does not override that method، then an error will result. 303In cases in which one interface inherits another، with both defining a common default method، the inheriting interface’s version of the method takes precedence.

30
Q

What is the general form of reference to a default implementation?

A

It is possible to refer explicitly to a default implementation by using a new form of super. Its general form is shown here: InterfaceName.super.methodName( )

31
Q

How does a static method work in an interface? What is its general form?

A

defined by an interface can be called independently of any object. Thus، no implementation of the interface is necessary، and no instance of the interface is required in order to call a static method. Instead، a static method is called by specifying the interface name، followed by a period، followed by the method name. Here is the general form: InterfaceName.staticMethodName

32
Q

Give me a code example that uses a private method in an interface.

A

version of the Series interface that adds a second default method called skipAndGetNextArray( ). It skips a specified number of elements and then returns an array that contains the subsequent elements. It uses a private method called getArray( ) to obtain an element array of a specified size. Code example to the right >

33
Q

What 2 things can call a private interface?

A

Beginning with JDK 9، an interface can include a private method. A private interface method can be called only by a default method or another private method defined by the same interface.

34
Q

What JDK did they allow an interface to have private interfaces?

A

The key benefit of a private interface method is that it lets two or more default methods use a common piece of code، thus avoiding code duplication.

35
Q

How do you instantiate an enumeration?

A

However، even though enumerations define a class type، you do not instantiate an enum using new. Instead، you declare and use an enumeration variable in much the same way that you do one of the primitive types. For example، this declares tp as a variable of enumeration type Transport: Transport tp;

36
Q

What are enumerations?

A

In its simplest form، an enumeration is a list of named constants that define a new data type. An object of an enumeration type can hold only the values that are defined by the list. Thus، an enumeration gives you a way to precisely define a new type of data that has a fixed number of valid values.

37
Q

What are some examples of real life enumerations?

A

Enumerations are common in everyday life. For example، an enumeration of the coins used in the United States is penny، nickel، dime، quarter، half-dollar، and dollar. An enumeration of the months in the year consists of the names January through December. An enumeration of the days of the week is Sunday، Monday، Tuesday، Wednesday، Thursday، Friday، and Saturday.

38
Q

What type of variables do enumerations replace?

A

you might use an enumeration to represent a set of status codes، such as success، waiting، failed، and retrying، which indicate the progress of some action. In the past، such values were defined as final variables، but enumerations offer a more structured approach.

39
Q

How do you create an enumeration in code? What are enumeration constants? What are self-typed constants?

A

An enumeration is created using the enum keyword. The identifiers CAR، TRUCK، and so on، are called enumeration constants. the enumeration constants’ type is the type of the enumeration in which the constants are declared، which is Transport in this case. Thus، in the language of Java، these constants are called self-typed، where “self” refers to the enclosing enumeration.

40
Q

What values can you assign to enumeration variables?

A

Because tp is of type Transport، the only values that it can be assigned are those defined by the enumeration. For example، this assigns tp the value AIRPLANE: tp = Transport.AIRPLANE; This text is using an example where the enum method defined airplane in its body and tp is a variable used outside the enum method.

41
Q

Can enumerations and switch statements interact?

A

An enumeration value can also be used to control a switch statement. Of course، all of the case statements must use constants from the same enum as that used by the switch expression. // Use an enum to control a switch statement switch(tp) { case CAR: // … case TRUCK: // … Notice that in the case statements، the names of the enumeration constants are used without being qualified by their enumeration type name. That is، TRUCK، not Transport.TRUCK، is used. This is because the type of the enumeration in the switch expression has already implicitly specified the enum type of the case constants.

42
Q

Create a code that demonstrates the values() and valueOf() enum methods?

A

the return type of Transport.valueOf(“TRAIN”) is Transport. The value returned is TRAIN. The following program demonstrates the values( ) and valueOf( ) methods: Code to the right >

43
Q

What does the valueOf() method return?

A

The valueOf( ) method returns the enumeration constant whose value corresponds to the string passed in str. Reminder that the general form for the valueOf() enumeration method is: public static enum-type valueOf(String str)

44
Q

What is the style recommended for naming constants in enumerations?

A

there is no rule that requires enumeration constants to be in uppercase. Because enumerations often replace final variables، which have traditionally used uppercase، some programmers believe that uppercasing enumeration constants is also appropriate. There are، of course، other viewpoints and styles.

45
Q

How does java implement enumerations and how is it more beneficial than how other languages implement enumerations?

A

Unlike the way enumerations are implemented in some other languages، Java implements enumerations as class types. Although you don’t instantiate an enum using new، it otherwise acts much like other classes. The fact that enum defines a class enables the Java enumeration to have powers that enumerations in some other languages do not. For example، you can give it constructors، add instance variables and methods، and even implement interfaces.

46
Q

What are the 2 methods that all enumerations automatically have?

A

All enumerations automatically have two predefined methods: values( ) and valueOf( ). Their general forms are shown here: public static enum-type[ ] values( ) public static enum-type valueOf(String str)

47
Q

What does the values() enumeration method return?

A

The values( ) method returns an array that contains a list of the enumeration constants.

48
Q

Give me a code example that includes an instance variable، a construction، and a method. All of these use enumerations.

A

The following version of Transport illustrates the use of a constructor، an instance variable، and a method. It gives each type of transportation a typical speed. Code example to the right >

49
Q

What 3 things can enumerations define? When are enumeration constructors called?

A

It is important to understand that each enumeration constant is an object of its enumeration type. Thus، an enumeration can define constructors، add methods، and have instance variables. When you define a constructor for an enum، the constructor is called when each enumeration constant is created. Each enumeration constant can call any method defined by the enumeration. Each enumeration constant has its own copy of any instance variables defined by the enumeration.

50
Q

How many overload forms do you need when using enumerations?

A

an enum can offer two or more overloaded forms، just as can any other class.

51
Q

What are the two important restrictions when it comes to enumerations?

A

There are two restrictions that apply to enumerations. First، an enumeration can’t inherit another class. Second، an enum cannot be a superclass. This means that an enum can’t be extended. Otherwise، enum acts much like any other class type. The key is to remember that each of the enumeration constants is an object of the class in which it is defined.

52
Q

Which superclass can you inherit when declaring an enum?

A

Although you can’t inherit a superclass when declaring an enum، all enumerations automatically inherit one: java.lang.Enum

53
Q

What are two predefined methods (of java.lang.Enum) are occasionally used?

A

Most often، you won’t need to use these methods، but there are two that you may occasionally employ: ordinal( ) and compareTo( ).

54
Q

What does the ordinal() method do and what is its general form?

A

The ordinal( ) method obtains a value that indicates an enumeration constant’s position in the list of constants. This is called its ordinal value. The ordinal( ) method is shown here: final int ordinal( ) It returns the ordinal value of the invoking constant. Ordinal values begin at zero.

55
Q

What does the compareTo() method do and what is its general form?

A

You can compare the ordinal value of two constants of the same enumeration by using the compareTo( ) method. It has this general form: final int compareTo(enum-type e) Here، enum-type is the type of the enumeration and e is the constant being compared to the invoking constant.

56
Q

Try this 12-1

A

Try This 12-1 A Computer-Controlled Traffic Light