Java SE 11 Programmer I Exam - Chapter VIII

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

What is the order of initialization for instances?

(1) If there is a superclass Y of X, then initialize the instance of Y first. (2) Process all instance variable declarations in the order they appear in the class. (3) Process all instance initializers in the order they appear in the class. (4) Initialize the constructor including any overloaded constructors referenced with this() .

What are the 7 main rules of order of initialization?

(1) The first statement of every constructor is a call to an overloaded constructor via this() , or a direct parent constructor via super() . (2) If the first statement of a constructor is not a call to this() or super() , then the compiler will insert a no-argument super() as the first statement of the constructor. (3) Calling this() and super() after the first statement of a constructor results in a compiler error. (4) If the parent class doesn't have a no-argument constructor, then every constructor in the child class must start with an explicit this() or super() constructor call. (5) If the parent class doesn't have a no-argument constructor and the child doesn't define any constructors, then the child class will not compile. (6) If a class only defines private constructors, then it cannot be extended by a top-level class. (7) All final instance variables must be assigned a value exactly once by the end of the constructor. Any final instance variables not assigned a value will be reported as a compiler error on the line the constructor is declared.

What are the four main rules of overriding a method?

(1) The method in the child class must have the same signature as the method in the parent class. (2) The method in the child class must be at least as accessible as the method in the parent class. (3) The method in the child class may not declare a checked exception that is new or broader than the class of any exception declared in the parent class method. (4) If the method returns a value, it must be the same or a subtype of the method in the parent class, known as covariant return types. Also the generics must match if there are any generics included.

What do object and reference types determine?

(1) The type of the object determines which properties exist within the object in memory. (2) The type of the reference to the object determines which methods and variables are accessible to the Java program. Casting objects can help to explicitly change reference so that certain properties of certain classes become accessible: Primate primate = new Lemur(); // Implicit Cast Lemur lemur2 = primate; // DOES NOT COMPILE (primate is a superclass to lemur) System.out.println(lemur2.age); Lemur lemur3 = (Lemur)primate; // Explicit Cast System.out.println(lemur3.age);

What is the difference between overriding and hiding a method?

- An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method. - If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass. - The distinction between hiding a static method and overriding an instance method has important implications: (1) The version of the overridden instance method that gets invoked is the one in the subclass. (2) The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

What's the difference between compile-time vs run-time?

- Compile-time is the time at which the source code is converted into an executable code while the run time is the time at which the executable code is started running. - Compile-time errors are the errors that occurred when we write the wrong syntax. If we write the wrong syntax or semantics of any programming language, then the compile-time errors will be thrown by the compiler. The compiler will not allow to run the program until all the errors are removed from the program. - The runtime errors are the errors that occur during the execution and after compilation. The examples of runtime errors are division by zero, etc. These errors are not easy to detect as the compiler does not point to these errors.

What is inheritance?

- Inheritance is the process by which a subclass automatically includes any public or protected members of the class, including primitives, objects, or methods, defined in the parent class. - Inheritance works across multiple classes, meaning if child class X inherits from parent class Y, which in turn inherits from a parent class Z, then class X would be considered a subclass, or descendant, of class Z.

How do you prevent a class from being inherited?

- Mark it as final. - If you try to define a class that inherits from a final class, then the class will fail to compile.

What are the two types on inheritance and which of them Java supports?

- Single and multiple inheritance. - Java supports single inheritance, by which a class may inherit from only one direct parent class (multiple children can inherit from one parent). - By design, Java doesn't support multiple inheritance in the language because multiple inheritance can lead to complex, often difficult-to-maintain data models. - Java supports implementing multiple interfaces.

When are classes loaded and determined?

- The rules for when classes are loaded are determined by the JVM at runtime. - For the exam, you just need to know that a class must be initialized before it is referenced or used. - Also, the class containing the program entry point, aka the main() method, is loaded before the main() method is executed.

How does Java know that my custom-created classes should allow object creation?

- When Java sees you define a class that doesn't extend another class, it automatically adds the syntax extends java.lang.Object to the class definition. - The result is that every class gains access to any accessible methods in the Object class. - For example, the toString() and equals() methods are available in Object ; therefore, they are accessible in all classes.

Thinking about the access modifiers which access modifiers enable the child class to use the parent class's memebers?

- When one class inherits from a parent class, all public and protected members are automatically available as part of the child class. - Package-private members are available if the child class is in the same package as the parent class. - Last but not least, private members are restricted to the class they are defined in and are never available via inheritance.

If a child cannot extend multiple classes, then how will a child class extend Object?

- When you define a new class that extends an existing class, Java does not automatically extend the Object class. - Since all classes inherit from Object , extending an existing class means the child already inherits from Object by definition. - If you look at the inheritance structure of any class, it will always end with Object on the top of the tree,

Do static and final variables have to be initialized just once?

- Yes. Kind of. - Static variables are the same across instances. Meaning if you assign a value to a static variable, then it will the same in all objects. - Instance variables marked final follow similar rules. They can be assigned values in the line in which they are declared or in an instance initializer. public class MouseHouse { private final int volume; private final String name = "The Mouse House"; { volume = 10; } }

What's constructor overloading?

A class can have multiple constructors, as long as their parameters are different.

What's an inner class?

A class defined inside another class.

How does a class implement an interface?

A class implements an interface by overriding the inherited abstract methods.

What is method hiding?

A hidden method occurs when a child class defines a static method with the same name and signature as an inherited static method defined in a parent class. All overriding rules apply with the addition that if the method is static in a parent class it must also be static in the child class. Additionally, method hiding is NOT overriding. Although they are almost the same - the @Override annotation won't work on hiding vs overriding. If one is marked static and the other is not then the code won't compile.

What is the order of initialization for classes?

(1) If there is a superclass Y of X, then initialize class Y first. (2) Process all static variable declarations in the order they appear in the class. (3) Process all static initializers in the order they appear in the class.

What makes a method a constructor?

- It has the exact name as the class it's in, and no return type.

What's a top-level class?

A top-level class is a class that is not defined inside another class.

When is an instance initialized?

Any time the 'new' keyword is used.

What is an instance variable>

Instance variable in Java is used by Objects to store their states. Variables that are defined without the STATIC keyword and are Outside any method declaration are Object-specific and are known as instance variables. They are called so because their values are instance specific and are not shared among instances.

When will Java not add a no-argument constructor?

Java will not add a no-argument constructor if one already exists. For example in this case, Java will not add a no argument constructor to the Mammal class. public class Mammal { public Mammal(int age) {} }

How many times can a final instance variable be assigned a value?

Only once. So this is invalid: public class MouseHouse { private final int volume; private final String type; { this.volume = 10; } public MouseHouse(String type) { this.type = type; } public MouseHouse() { // DOES NOT COMPILE this.volume = 2; // DOES NOT COMPILE } } - The second constructor does not compile for two reasons. First, the constructor fails to set a value for the type variable. The compiler detects that a value is never set for type and reports an error on the line where the constructor is declared. - Second, the constructor sets a value for the volume variable, even though it was already assigned a value by the instance initializer.

How do you reference a variable that is in the parent class?

Use they keyword 'super': super.type = type; This works even if there is a variable of the same name in super and child class. Then do something like this: super.type = this.type;

When is an import statement required?

When two classes are NOT in the same package.

Is String a subtype of CharSequence?

Yes, String implements CharSequence.

Can you assign a null value to a final instance variable?

Yes, as long as it's a reference variable and not a primitive.

What's the full syntax for defining a class?

(1) Access modifier (2) Abstract or final keyword (optional) (3) 'class' keyword (required) (4) class name (required) (5) extends another class (optional) (6) class body for variables and methods (optional) public final class MyClass extends MySuperClass {}

Overall - in what order are things initialized when you do this: Mammal mammal = new Mammal();

(1) First all super class is initialized. (2) Then current class static variables are initialized. (3) Then instance (non-static) variables are initialized. (4) Then constructor completes it's work.

What is compile-time vs run-time polymorphism?

- Compile-time polymorphism is achieved through method overloading. - The runtime polymorphism can be achieved by method overriding. The JVM determines the proper method to call at the runtime, not at the compile time.

What is the result of this code snippet? public double getAverageWeight() { return getAverageWeight() + 20; }

A StackOverflowError because the method calls itself cursively and indefinitely.

Why are these three all equivalent? public class Donkey {} public class Donkey { public Donkey() {} } public class Donkey { public Donkey() { super(); } }

Because Java will convert the first two to the third one.

Which method takes precedence: (1) printName(int a) in the Arthropod class (2) printName (int a) in the Spider class (extends Arthropod) When you create an object like this? Arthropod a = new Spider(); a.printName(10);

Because of polymorphism, the overridden method replaces the method on all calls, even if arthropod reference variable is used, as is done here.

Why does this not compile? And how can you make it compile? public class LongTailAnimal { protected void chew(List<Object> input) {} } public class Anteater extends LongTailAnimal { protected void chew(List<Double> input) {} // DOES NOT COMPILE }

Both of these examples fail to compile because of type erasure. In the compiled form, the generic type is dropped, and it appears as an invalid overloaded method.

If you call a constructor within a constructor, then where in the method can you place the call to another constructor?

Calling a constructor or this() in a another constructor has to be the FIRST line in that constructor. Same with using super().

What is overriding?

In Java, overriding a method occurs when a subclass declares a new implementation for an inherited method with the same signature and compatible return type. Remember that a method signature includes the name of the method and method parameters. When you override a method, you may reference the parent version of the method using the super keyword. In this manner, the keywords this and super allow you to select between the current and parent versions of a method, respectively. If you don't use 'this' or 'super' then Java automatically calls the current or child class method and not the parent class method.

In addition to the same line and an initializer block - when else can final variables be assigned a value?

In the constructor. The constructor is part of the initialization process, so it is allowed to assign final instance variables in it. For the exam, you need to know one important rule. By the time the constructor completes, all final instance variables must be assigned a value.

What does this print? public class Animal { static { System.out.print("A"); } } public class Hippo extends Animal { static { System.out.print("B"); } public static void main(String[] grass) { System.out.print("C"); new Hippo(); new Hippo(); new Hippo(); } }

It prints ABC exactly once. Since the main() method is inside the Hippo class, the class will be initialized first, starting with the superclass and printing AB . Afterward, the main() method is executed, printing C . Even though the main() method creates three instances, the class is loaded only once.

What does super() refer to if you use it in your own custom class that doesn't extend anything?

It will refer to java.lang.Object.

If the current and super class both have the same variable and you don't use 'this' or 'super' to call it - then which variable will be accessed first?

Java checks outward starting with the narrowest scope. For this reason, the variable from the current class would be accessed first followed by the super class.

What is polymorphism?

Java supports polymorphism , the property of an object to take on many different forms. To put this more precisely, a Java object may be accessed using a reference with the same type as the object, a reference that is a superclass of the object, or a reference that defines an interface the object implements, either directly or through a superclass.

How many interfaces can a class implement?

Multiple.

Can you override a private method?

No because they are not inherited. Java permits you to redeclare a new method in the child class with the same or modified signature as the method in the parent class. This method in the child class is a separate and independent method, unrelated to the parent version's method, so none of the rules for overriding methods is invoked.

Can variables be overridden?

No variables can only be hidden.

Does Java allow variables to be overridden?

No, but they can be hidden. A hidden variable occurs when a child class defines a variable with the same name as an inherited variable defined in the parent class. This creates two distinct copies of the variable within an instance of the child class: one instance defined in the parent class and one defined in the child class.

Can a constructor call itself?

No, that results in a compile error.

Which methods can call this() or super()?

Only constructors.

Are these consider overloaded or overridden methods? public class LongTailAnimal { protected void chew(List<Object> input) {} } public class Anteater extends LongTailAnimal { protected void chew(ArrayList<Double> input) {} }

Overloaded because the signatures differ.

Whats the difference between overloading and overriding a method?

Overloading = the return type and parameters can differ. Overriding = return type and parameters must be the same (or the return type of the sub-class method must be a subtype of the return type in the super class method). For example, if the super class method returns a List then a subclass overridden method can return a List or an ArrayList.

When do static variables vs static final vs final variables need to be initialized?

Regular or static variables can be initialized whenever (either inside the class or later when an object has been created. However when the keyword final is in front, the variable (static or not) HAS to be assigned a value by the time constructor completes. This could happen in the declaration line, initializer block, or in the constructor. Assigning a value to final variables could also happen in a constructor that is then called by another constructor. Failure to do so will result in a compiler error.

What is the first line of any constructor?

Remember, the first line of every constructor is a call to this() or super() , and if omitted, the compiler will automatically insert a call to the parent no-argument constructor super(). You can't have both this() and super() in a single constructor!!

If and how can you extend a class that is not private but has private constructors?

The answer is "yes," but only an inner class defined in the class itself can extend it. An inner class is the only one that would have access to a private constructor and be able to call super() . Other top-level classes cannot extend such a class. This is not on the exam.

How can final methods be inherited?

They cannot. By marking a method final , you forbid a child class from replacing this method. This rule is in place both when you override a method and when you hide a method. In other words, you cannot hide a static method in a child class if it is marked final in the parent class. But you can overload a final method. Meaning if the parameters are different in the child class, then the code will compile.

Why does this not compile? public class Mammal { public Mammal(int age) {} } public class Elephant extends Mammal { // DOES NOT COMPILE }

This does not compile because at compile time Java will try to insert a no argument constructor into Elephant, and then call super() with it: public class Elephant extends Mammal { public Elephant() { super(); // DOES NOT COMPILE } } However, the super() requires a parameter, because the Mammal class constructor takes in an int. Therefore this can be fixed by doing this: public class Elephant extends Mammal { public Elephant() { super(10); } } This will now work too: public class AfricanElephant extends Elephant {}

What's a default no-argument constructor?

When a constructor is not explicitly defined, then Java still creates one for you without any parameters or body. public Rabbit() {} It is generated during compile time. And will be visible in the .class file.

Can this.myVariable refer to both a variable in the current and parent class?

Yes! You can access a parent variable with 'this' and with 'super'. Assuming that the child class does not have a variable with the same name. Because if it does, then 'this' will call the current class's variable and not the parent class one.

Can an object that implements an interface be assigned to a reference for that interface?

Yes, an object that implements an interface can be assigned to a reference for that interface.

Can an overridden method declare an exception?

Yes, an overridden method may declare a new exception, provided it is not checked.

Can constructors be private?

Yes.

If the return type of a method is an reference type (i.e. a subclass of Object), can the method return just null?

Yes.

Is variable hiding the same as method hiding?

Yes.

Is this valid? public MouseHouse() { this(null); }

Yes. MouseHouse() is clearly a no-argument constructor that calls another constructor that has an Object as a parameter. Probably the other constructor looks something like this: public MouseHouse(String s) {this.s = s}.

Is this valid? public class Mammal { ===public int legs = 4; ===public static void main (String[] args) { ======System.out.println(Mammal.legs); ===} }

Yes. Since the main method is IN Mammal class, it can just call Mammal.legs.

Can one constructor call another in the same class by name without using 'this'?

Yes. You can only call another constructor in the same class by using 'new'. Or you can use this. You can't just use the name: Mammal () { this(10); } // valid Mammal () { new Mammal(10); } // valid Mammal () { Mammal(10); } // NOT valid

What happens when a setter parameter and class variable have the same name? And then you try to use the setter to set the variable?

You need to use 'this' in front of the class variable. Otherwise Java won't assign the value. So do this: this.color = color; Instead of: color = color;

If you have two constructors and want to call one within another, then this compiles but not recommended to use: public Hamster(int weight) { new Hamster(weight, "brown");

You should use 'this' to call a constructor: public Hamster(int weight) { this(weight, "brown"); }


Kaugnay na mga set ng pag-aaral

Physiology 2 final, practice questions

View Set

GO! Excel 2016 Chapter 3 Practice Exam

View Set

Mortgages, Financing A Car, Financial Math Sem 2, Leasing vs. Buying a Car, Test, mortgages, buying vs.renting a home, Buying vs. Renting a Home Practice/Quiz, Topic Test - Mathematical Models with Applications, Annuities - Mathematical Models with A...

View Set

Adult Nursing: Integumentary System

View Set

Anatomy & Physiology - Module 2 Exam - Tissues and Skin

View Set

AP psychology study set from whole year

View Set

APUSH: Chapter 9 study questions

View Set