Programming Final Exam

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

String (String str)

Constructor: creates a new string object with the same characters as str.

Constructors and inheritance

Constructors are not inherited. Default constructor: public Employee(){ super(); // calls StaffMember() constructor } Constructor needs to call super-class constructors explicitly: public Employee (String name, String address, String phone, String socSecNumber, double rate) { super (name, address, phone); socialSecurityNumber = socSecNumber; payRate = rate; } The super call must be the first statement in the constructor.

What is the syntax of using inheritance?

Creating a subclass, general syntax: public class <name> extends <superclass name> { Example: public class Employee extends StaffMember { .... }

In a static method, you may use the this parameter either explicitly or implicitly.

F

Java allows an instance of an abstract class to be instantiated

F

You cannot derive an interface from a base interface

F

Inheritance: FAQ

How can a subclass call a method or a constructor defined in a super-class? Use super() or super.method() Does Java support multiple inheritance? No. Use interfaces instead What restrictions are placed on method overriding? Same name, argument list, and return type. May not throw exceptions that are not thrown by the overridden method, or limit the access to the method Does a class inherit the constructors of its super-class? No. Need to call them explicitly

Polymorphism and casting

It's legal for a variable of a super-class to refer to an instance of a subclass. When a primitive type is used to store a value of another type (e.g. an int in a double variable) conversion takes place. When a subclass is stored in a superclass no conversion occurs!

ArrayIndexOutOfBoundsException is a descendent of the class RuntimeException. This means:

The exception does not have to be explicitly caught

What is the most important function of a constructor?

To allocate memory when the new keyword is encountered

When to use abstract classes

To represent entities that are insufficiently defined Group together data/behavior that is useful for its subclasses

The ____ is the one Java provides by default.

default constructor ex: public Dog() { }

Whats the new access modifier that comes with inheritance?

protected - can be seen/used within class and any subclass.

String replace (char oldChar, char newChar)

returns a new string that is identical with this string except that every occurrence of oldChar is replaed by newChar

char charAt (int index)

returns the character at the specified index.

How comparing objects should look like

// Returns whether o refers to a StaffMember // object with the same name public boolean equals(Object o) { if (o instanceof StaffMember) { StaffMember other = (StaffMember) o; return name.equals(other.name); } else { return false; } }

When used with objects, what is the equality (==) operator comparing?

== compares object references/ checks that two objects have the same memory address.

Abstract classes

An abstract class: can leave one or more method implementations unspecified An abstract method has no body (i.e. no implementation). Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class. abstract public class abstract-base-class-name { public abstract return-type method-name(params); ... } public class derived-class-name { public return-type method-name(params) { statements; } ... }

Subtype principles

An instance of a subclass can always be used when an instance of a superclass is expected A subclass object can be: Assigned to a variable of the subclass type Passed to a method that expects the superclass type as a parameter The reverse is NOT true - a superclass object cannot be used where a subclass object is expected The instanceof operator can be used to check the type of the object stored in the variable. A cast can be used to convert a superclass variable to a subclass variable if you know the variable contains a subclass object

Assuming that str is declared as follows, String str = "RSTUVWXYZ"; what value will be returned from str.charAt(5)? A) X B) V C) W D) U

C: W

Subclass constructors

Can use the keyword super as the first line of code in a body to call a superclass constructor Implicitly call the default (0 arguments) superclass constructor if super is not used to explicitly call a superclass constructor If the superclass has no default constructor and super is not used to call a superclass constructor, an error results

What is overloading?

Can you write different methods that have the same name? Yes! public int sum(int num1, int num2){ return num1 + num2; } public int sum(int num1, int num2, int num3){ return num1 + num2 + num3; } A method's name + number, type, and order of its parameters: method signature The compiler uses a method's signature to bind a method invocation to the appropriate definition

A method or instance variable modified by protected:

Cannot be accessed by name outside of the package

What is the output of the following program? class Base { protected void foo() { System.out.println("Base Foo called "); } } class Derived extend Base { void foo() { System.out.println("Derived Foo called "); } } public class Main { public static void main(String args[]) { Derived d = new Derived(); d.foo(); } }

Compilation error. Foo in class Base is protected and attempting to override it in Derived will not work.

A class with no abstract methods is called a

Concrete class

Everything is an Object?

Every class in Java implicitly extends the Java Object class. Therefore every Java class inherits all the methods of the class Object, such as equals(Object other) toString() Often we want to override the standard implementation Note the difference between overloading and overriding!

An interface specifies the headings and definitions for methods that must be defined in any class that implements the interface.

F

If the final modifier is included before the definition of the method, then the method can be redefined in a derived class.

F

There are only two ways to build classes from other classes: inheritance and polymorphism

F

When an exception is thrown, the code in the surrounding try block continues executing and then the catch block begins executing.

F

An abstract class can be instantiated when all of the methods are complete.

False - an abstract class is incomplete and cannot be instantiated, but can be used as a base class.

Arrays of a subclass type can store any supertype as elements

False - subclass elements may be stored in an array of superclass.

When private methods are meant to be part of the implementation and not the public interface, the methods are invoked

From within the class

Reusable classes tend to have

Interfaces that are more abstract than concrete

Every class in Java implicitly extends what Java class ?

Object

Constructors Implementing "This"

One constructor can call another using this: public class Point { private int x; private int y; public Point() { this(0, 0); //calls the (x, y) constructor } public Point(int x, int y) { this.x = x; this.y = y; } ... }

instanceof operator in this context

Pet p = new Pet(); Pet q = new Cat(); // class Cat extends Pet Cat r = new Cat(); Then, (p instanceof Pet) == true (p instanceof Cat) == false (q instanceof Pet) == true (q instanceof Cat) == true (r instanceof Pet) == true (r instanceof Cat) == true

Polymorphism defined

Polymorphism: the ability for the same code to be used with several different types of objects and behave differently depending on the actual type of object used. Example: for (int count=0; count < staffList.length; count++) { amount = staffList[count].pay(); // polymorphic }

String concat (String str)

Returns a new string consisting of this string concatenated with str.

____ makes it explicit in the code, that you're constructing the base class using the no-arg constructor.

Super constructor

A cast can be used to convert a superclass variable to a subclass variable if you know the variable contains a subclass object

T

A subclass inherits attributes from its superclass, which allows it to perform as a subclass

T

An abstract method serves as a placeholder for a method that muse be defined in all derived classes.

T

An inner class definition is local to the outer class definition.

T

Generalization-specialization is the idea that as you make your way down the inheritance tree, things get more specific.

T

In most cases, there is no reason to build a class if it is not going to interact with other classes

T

Inheritance and composition have one significant difference in the way objects are built. When inheritance is used, the end result is a single class that incorporates all the behaviors and attributes of the inheritance hierarchy. When composition is used, one or more classes are used to build another class.

T

Java source code that contains a class with an inner class, when compiled, will produce a separate .class file for the inner class.

T

The String class's valueOf( ) method accepts a value of any primitive data type as an argument and returns a string representation of the value. A) True B) False

T

The throw operator causes a change in the flor control

T

Wrapper classes provide a class type corresponding to each of the primitive types so that you can have class types that behave somewhat like primitive types.

T

If you were going to catch an exception of type Exception along with catching other exceptions, where should this catch block be placed within your code?

The catch box should be placed at the last to avoid interruption of the normal flow caused by exception. If put ( catch (exception e)) first, then in case of any exception this block will execute.

Given the following statement, which of the following is NOT true? str.insert(8, 32); A) The starting position for the insert is 8 B) str is a StringBuilder type object C) The insert will start at position 32 D) The literal number 32 will be inserted

The insert will start at position 32

Calling overridden methods

The new method often relies on the overridden one. A subclass can call an overridden method with the super keyword. Calling an overridden method, syntax: super.<method name> ( <parameter(s)> ) public class Executive extends Employee { public double pay() { double payment = super.pay() + bonus; bonus = 0; return payment; }

How does typecasting help with the equals method?

The object that is passed to equals can be cast from Object into your class's type. Example: public boolean equals(Object o) { StaffMember other = (StaffMember) o; return name.equals(other.name); } Type-casting with objects behaves differently than casting primitive values. We are really casting a reference of type Object into a reference of type StaffMember. We're promising the compiler that o refers to a StaffMember object, and thus has an instance variable name

Notes about polymorphism

The program doesn't know which pay method to call until it's actually running. This has many names: late binding, dynamic binding, virtual binding, and dynamic dispatch. You can only call methods known to the super-class, unless you explicitly cast. You cannot assign a super-class object to a sub-class variable (a cow is an animal, but an animal is not a cow! )

Is the return value part of the method's signature?

The return value is not part of the signature You cannot overload on the basis of the return type (because it can be ignored) Example of invalid overloading: public int convert(int value) { return 2 * value; } public double convert(int value) { return 2.54 * value; }

Use the __________ statement to indicate that a problem has occurred.

Throw

Assigning an object of a derived class to a variable of a base class is called:

Upcasting

Polymorphism and parameters

You can pass any subtype of a parameter's type. public class EmployeeMain { public static void main(String[] args) { Executive lisa = new Executive(...); Volunteer steve = new Volunteer(...); payEmployee(lisa); payEmployee(steve); } public static void payEmployee(StaffMember s) { System.out.println("salary = " + s.pay()); } }

Why the equals method does not work at first.

You might think that the following is a valid implementation of the equals method: public boolean equals(Object other) { if (name.equals(other.name)) { return true; } else { return false; } } However, it does not compile. StaffMember.java:36: cannot find symbol symbol : variable name location: class java.lang.Object Why? Because an Object does not have a name instance variable.

What is the output of the following program? Explain public class StringOper { public static void main(String [] args) { String s1 = "abc"; String s2 = "def"; String s3 = s2; s2 = "ghi"; System.out.println(s1 + s2 +s3); } }

abcghidef o Before system has a chance to print out, s2's original memory is changed.

____allows to have more than one constructor inside one Class.

constructor overloading

enumerated type

defined and then used as the type of a variable when it is declared; establishes all possible values of a variable of that type by listing, or enumerating, them. the values are identifiers, and can be anything desired

A(n) __________ declaration contains a comma-separated list of constants.

enum

example of enumerated type

enum Season {winter, spring, summer, fall} there is no limit to the number of values that you can list for an enumerated type. once the type is defined, a variable can be declared of that type: Season time; the variable time is now restricted in the values it can take on. It can hold one of the four Season values, but nothing else.

Explain what a call to super( ) call does in a constructor of a derived class.

he super() calls a superclass default constructor.

num=Integer.parseInt(str);

if the string object str holds the string "987", the following line of code converts the string into the integer variable 987 and stores that value in the int variable num:

What is inheritance?

inheritance: A way to create new classes based on existing classes, taking on their attributes/behavior. a way to group related classes a way to share code between classes A class extends another by absorbing its state and behavior. super-class: The parent class that is being extended. sub-class: The child class that extends the super-class and inherits its behavior. The subclass receives a copy of every field and method from its super-class. The subclass is a more specific type than its super-class (an is-a relationship)

all wrapper classes are defined in which package?

java.lang package

The constructor which takes no arguments is called the ____.

no-argument constructor

What is responsibility of Garbage Collector? What is purpose of overriding finalize() method?

o Garbage Collector reclaims memory used by an object o Overriding finalize() when class has resources that won't be cleaned up by the Garbage Collector.

What is overriding a method?

override: To write a new version of a method in a subclass that replaces the super-class's version.

How can you implement toString?

public String toString() { code that returns a suitable String; } Example: toString() method for our Student class: public String toString(){ return "name: " + name+ "\n" + "id: " + id + "\n" + "average: " + average; } Every class does NOT have to specify a toString(). Classes have a default.

Vehicle -int numberOfWheels +Vehicle() #Vehicle(int wheels) +int getNumberofWheels() +Boolean hasEngine Car(Inherits from Vehicle) Bicycle (Inherits from Vehicle) Motorcycle (Inherits from Bicycle) • Consider the class hierarchy of vehicles shown in the Figure above, with the following additional information: Consider the class hierarchy of vehicles shown in the Figure above, with the following additional information: • Cars always have four wheels; • Bicycles and their subclasses always have two wheels. Note: there are only default (i.e., parameter-less) constructors available in the subclasses. 1. Convert the class hierarchy in Figure 1 to Java. Provide implementation to all the methods. 2. Write the implementation of the main() method as a test drive to instantiate an object of each class type and sore all the instantiated objects in a single VehiclesArray. 3. For each of the following statements pertinent to classes of the hierarchy state whether they are acceptable or not in Java and give a brief (no more than two lines) explanation why it is or is not the case. a) Vehicle v1 = new Vehicle(); b) Vehicle [] v2 = new Vehicle[3]; c) Vehicle v3 = new MotorCycle(); d) Bicycle b = new MotorCycle(); e) //Car c1 = new Bicycle (); f) Vehicle v4 = new MotorCycle(); g) Car c2 = (Car) v4; h) Vehicle v5 = new Car(); i) Car c3 = (Car) v5;

public class Vehicle { int numberOfWheels; private boolean hasEngine; Vehicle (){ } Vehicle(int wheels){ } public int getNumberOfWheels(){ return numberOfWheels; } public boolean hasEngine(){ return hasEngine; } } class Car extends Vehicle{ final int numberOfWheels = 4; } class Bicycle extends Vehicle{ final int numberOfWheels = 2; } class MotorCycle extends Bicycle{ final int numberOfWheels = 2; } public static void main(String[] args) { Vehicle v1 = new Vehicle(); - acceptable Because v1 is an object of class Vehicle and it is instantiating it giving it a new memory location. Vehicle [] v2 = new Vehicle[3]; - acceptable it is creating array of an object v2 and then giving the array size of 3. Vehicle v3 = new MotorCycle(); - acceptable, similar to v1, however it is giving the new memory location to inside of MotorCycle. Bicycle b = new MotorCycle(); - acceptable similar to v1, however it is giving the new memory location to inside of MotorCycle from bicycle Car c1 = new Bicycle(); - not acceptable bicycle cannot be converted to car Vehicle v4 = new MotorCycle(); Car c2 = (Car) v4; - not acceptable MotorCycle cannot be cast to car Vehicle v5 = new Car(); Car c3 = (Car) v5; - acceptable car can cast to car }

When you use the assignment operator with variables of a class type, you are assigning a

reference

wrapper class 2.0

represents a particular primitive type. for example: Integer age0bj=new Integer(40); once this declaration and instantiation are performed, the age0bj object effectively represents the integer 40 as an object. it can be used wherever an object is needed in a program rather than a primitive type

boolean equals (String str)

returns a new string consisting of this string concatenated with str.

String toUpperCase ( )

returns a new string identical to this string except all lowercase letters are converted to their uppercase equivalent.

String toLowerCase ( )

returns a new string identical to this string except all uppercase letters are converted to their lowercase equivalent.

String substring (int offset, int endIndex)

returns a new string that is a subset of this string starting at index offset and extending through endIndx-1;

int compareTo (String str)

returns an integer indicating if this string is lexically before, equal to, or lexically after the string str.

static int parseInt (String str)

returns the int corresponding to the value stored in the specified string

int length( )

returns the number of characters in this stirng.

boolean equalsIgnoreCase (String str)

returns true if this string contains the same characters as str (without regard to case) and false otherwise.

A(n) __________ variable represents classwide information that's shared by all the objects of the class.

static

A(n) ___ imports all static members of a class

static import on demand

What is toString()?

tells Java how to convert an object into a String called when an object is printed or concatenated to a String: Point p = new Point(7, 2); System.out.println("p: " + p); Same as: System.out.println("p: " + p.toString()); Every class has a toString(), even if it isn't in your code. The default is the class's name and a hex (base-16) hash-code:

autoboxing

the automatic conversion between a primitive value and a corresponding wrapper object. for example, in the following code, an int value is assigned to an Integer object reference variable: Integer obj1; int num1=69; obj1=num1; //automatically creates an Integer object

polymorphism

the idea that we can refer to multiple types of related objects over time in consistent ways. it gives us the ability to design powerful and elegant solutions to problems that deal with multiple objects.

When an instance method is called for a particular object, the method's body implicitly uses what keyword to refer to the object's instance variables and other methods?

this

Every object can access a reference to itself with keyword ___.

this (sometimes called the this reference)

What is 'This'?

this : A reference to the current instance of a given class using this: To refer to an instance variable: this.variable To call a method: this.method(parameters); To call a constructor from another constructor: this(parameters);

this and super in constructors

this(...) calls a constructor of the same class. super(...) calls a constructor of the superclass. Both need to be the first action in a constructor.

static methods are invoked

through their class names instead of through objects of that class

An object's __________ method is called implicitly when an object appears in code where a String is needed.

toString

wrapper class

used when we create an object that serves as a container to hold various types of other objects, and we want the object to hold a simple integer value. In this case, we need to "wrap" a primitive value into an object

not only can methods be static, but

variables can be static as well; we declare static class members using the static modifier

what do wrapper classes provide?

various methods related to the management of the associated primitive type. for example, the Integer class contains methods that return the int value stored in the object and that convert the stored value to other primitive types. note that the wrapper classes also contain static methods that can be invoked independent of any instantiated object.

for each primitive type in Java, there exists a corresponding

wrapper class in the Java class library.


Kaugnay na mga set ng pag-aaral

GUIDED READING AND TEXTBOOK QUESTIONS 5-6

View Set

UNIT 11 quiz questions (module 32)

View Set

Ch. 11 PrepU Practice Questions combined

View Set

Chapter 12: Humanistic Psychology, Positive Psychology, and the science of happiness

View Set

Unit 4 Topic 7 - Learning Part 2

View Set