ch5 Flashcards
Where do all classes inherit from a single class called?
java.lang.object
public class Zoo extends java.lang.object{}
Does java.lang.Object have a parent class?
java.lang.Object is the only class that doesn’t have any
parent classes.
What are the rules?
1.The first statement of every constructor is a call to another constructor within the class
using this(), or a call to a constructor in the direct parent class using super().
- The super() call may not be used after the first statement of the constructor.
- If no super() call is declared in a constructor, Java will insert a no-argument super()
as the first statement of the constructor. - If the parent does have argument constructor and the child doesn’t define any
constructors, the compiler will throw an error and try to insert a default no-argument
constructor into the child class. - If the parent does argument constructor, the compiler requires an explicit call to a parent constructor in each child constructor.
Explicit call
~~~
public class Mammal {
public Mammal(int age) {
}
}
public class Elephant extends Mammal {
public Elephant() {
super(10);
}
}
~~~
What does it print?
~~~
class Primate {
public Primate() {
System.out.println(“Primate”);
}
}
class Ape extends Primate {
public Ape() {
System.out.println(“Ape”);
}
}
public class Chimpanzee extends Ape {
public static void main(String[] args) {
new Chimpanzee();
}
}
~~~
Primate
Ape
what is the difference between super() and super?
super(), explicitly calls a parent constructor and may only be used in
the first line of a constructor of a child class.
The second, super, is a keyword used to reference a member defined in a parent class and may be used throughout the child class
what are the checks performed by compiler when you override?
The method in the child class must have the same signature as the method in the parent
class.
The method in the child class must be at least as accessible or more accessible than the
method in the parent class.
The method in the child class may not throw a checked exception that is new or
broader than the class of any exception thrown in the parent class method.
If the method returns a value, it must be the same or a subclass of the method in the
parent class, known as covariant return types.
What method cannot be overriden?
final method
How do you hide a variable?
When you hide a variable, you define a variable with the same name as a variable in a parent class
What is an abstract method?
An abstract method is a method marked with the abstract keyword defined in an
abstract class, for which no implementation is provided in the class in which it is declared.
What can abstract class contain?
an abstract class may include nonabstract methods and variables.
Can an abstract method be declared in a regular class?
an abstract
method may only be defined in an abstract class.
Will the following compile
~~~
public abstract class Turtle {
public abstract void swim() {}
public abstract int getAge() {
return 10;
}
}
~~~
Needs to be the following :
public abstract void swim() {} ;
Has a body for getAge();
Can an abstract class be final?
No bc the sole purpose of abstract classes is to be implemented by another class
Does the following compile?
~~~
public abstract class Whale {
private abstract void sing();
}
public class HumpbackWhale extends Whale {
private void sing() {
System.out.println(“Humpback whale is singing”);
}
}
~~~
public abstract class Whale {
private abstract void sing(); this does not compile
}
public class HumpbackWhale extends Whale {
private void sing() {
System.out.println(“Humpback whale is singing”);
}
}
Make a abstract class?
public abstract class A{}
What keywords are automatically added to abstract methods?
public.
Can an abstract class be protected, private, default?
no only public. even if you dont put public, it will automatically add public.
not even static
What is inheritance?
Inheritance is the process by which the new child subclass automatically includes any
public or protected primitives, objects, or methods defined in the parent class
Can a child access private memeber?
Finally, a child class may never access a private member of the parent class, at least not
through any direct reference
What does java support single? mutiple?
Java supports single inheritance, by which a class may inherit from only one direct parent class. Java also supports multiple levels of inheritance, by which one class may extend
another class, which in turn extends another class. You can extend a class any number of
times, allowing each descendent to gain access to its ancestor’s members.
Does java support multiple inheritance?
no diamond problem
can lead to complex, often diffi cult-to-maintain code.
What is the concrete class?
the first nonabstract susbclass that extends an abstract class and is required to implement all the inherited abstract method
What is the output and why?
~~~
public abstract class Animal {
public abstract String getName();
}
public class Walrus extends Animal {
}
public abstract class Eagle extends Animal {
}
~~~
public abstract class Animal { public abstract String getName(); } public class Walrus extends Animal { //does not compile } public abstract class Eagle extends Animal { //compiles }
- Because concrete classes need to implement the inherited methods
- abstract classes does not need to implement the inherited methods
What are the rules of abstract class definitions?
- Abstract classes cannot be instantiated directly
- It can be defined with any number, including zero of abstract and non-abstract methods
- They cannot be marked private or final, protected.
- An abstract class that extends another abstract class inherits all of its abstract methods as its own abstract methods
- The first concrete class that extends an abstract class must provide an implementation for all the inherited abstract methods.
What are the rules of abstract method definitions?
- Abstract methods may only be defined in abstract classes.
- Abstract methods may not be declared private or final.
- Abstract methods must not provide a method body/implementation in the abstract
class for which is it declared. - Implementing an abstract method in a subclass follows the same rules for overriding a method. For example, the name and signature must be the same, and the visibility of
the method in the subclass must be at least as accessible as the method in the parent
class.
Will it compile?
public abstract class Whale {
protected abstract void sing();
}
public class HumpbackWhale extends Whale {
private void sing() {
System.out.println(“Humpback whale is singing”);
}
}
public abstract class Whale {
protected abstract void sing();
}
public class HumpbackWhale extends Whale {
private void sing() { // DOES NOT COMPILE
System.out.println(“Humpback whale is singing”);
}
}
No because the child is not accessible
What is an interface?
An interface is an abstract data type that defines a list of abstract public methods that any class implementing the interface must provide.
public abstract interface CanBurrow{
}
What are the rules of an interface?
It cannot be instantiated directly
Not required to have any methods
cannot be marked final
must have public/default access. anything else will give compile error
all methods in an interface need to have abstract/public
An interface ____ another interface?
extends
an abstract class _____ another abstract class
extends
What are the rules of interface variables?
- They are public, static and final
No private/Protected -> compile error - if marked as final must be declared a value.
Even if you do
public int MAX = 90;
compiler will make it
public static final int MAX =90;
Make an interface code.
public abstract interface Can(){} //PUBLIC
abstract interface Cann(){} //Default
what is a default method?
method with a default keyword.
1. may be only declared within an interface but not within a class/abstract class
2. marked with default keyword
3. not static, final or abstract (maybe overridden)
4. must be public. cannot be private/protected
5. should have implementation
6. cannot be static
Can a class implement multiple interfaces?
A class may implement multiple interfaces
Why will this not compile? Is there a way to make it work?
~~~
public interface Walk {
public default int getSpeed() {
return 5;
}
}
public interface Run {
public default int getSpeed() {
return 10;
}
}
public class Cat implements Walk, Run { // DOES NOT COMPILE
public static void main(String[] args) {
System.out.println(new Cat().getSpeed());
}
}
~~~
it is not clear whether the code should output 5 or 10. The answer is that the code
outputs neither value—it fails to compile.
If a class implements two interfaces that have default methods with the same name and
signature, the compiler will throw an error
Yes override the method.
public class Cat implements Walk, Run { public int getSpeed() { return 1; } public static void main(String[] args) { System.out.println(new Cat().getSpeed()); } }
Can you do this?
public interface CanFly {
void fly(int speed);
abstract void takeoff();
public abstract double dive();
}
Compiler will automatically insert
1. public abstract
2. public abstract
3. public
public abstract interface CanFly {
public abstract void fly(int speed);
public abstract void takeoff();
public abstract double dive();
}
What is static method?
- Like all methods in an interface, a static method is assumed to be public and will not
compile if marked as private or protected. - To reference the static method, a reference to the name of the interface must be used.
also
A static method defined in an interface
is not inherited in any classes that implement the interface
Does the following compile? Why? Why not?
private final interface CanCrawl {
private void dig(int depth);
protected abstract double depth();
public final void surface();
}
private final interface CanCrawl { // DOES NOT COMPILE
private void dig(int depth); // DOES NOT COMPILE
protected abstract double depth(); // DOES NOT COMPILE
public final void surface(); // DOES NOT COMPILE
}
If a static method is defined in an interface, how does inheritance work?
the classes that implements that interface will not be able to inherited.
Make a static method in the interface
public abstract interface Lucky {
public static final String LUCK = “Luck is always in my favor”;
public static void lucky() {
System.out.println(LUCK);
System.out.println(“I will be super rich”);
}
}
public class Nilima implements Lucky{
public static void main(String[] args) {
Lucky.lucky();
Nilima.lucky();//cant do this.
} }
What can you inherit from the parent class?
public and protected members of the parent class
What will compiler turn this into?
public interface CanSwim {
int MAXIMUM_DEPTH = 100;
final static boolean UNDERWATER = true;
public static final String TYPE = “Submersible”;
}
public interface CanSwim {
public static final int MAXIMUM_DEPTH = 100;
public static final boolean UNDERWATER = true;
public static final String TYPE = “Submersible”;
}
public class Canine {
public double getAverageWeight() {
return 50;
}
}
public class Wolf extends Canine {
public double getAverageWeight() {
return getAverageWeight()+20;
}
public static void main(String[] args) {
System.out.println(new Canine().getAverageWeight());
System.out.println(new Wolf().getAverageWeight());
}
}
what does the child return?
infinite loop
do
super.getAverageWeight();
Will the following compile?
public interface CanDig {
private int MAXIMUM_DEPTH = 100;
protected abstract boolean UNDERWATER = false;
public static String TYPE;
}
- cant be private. Must be public
- Cannot be protected. Must be public
- Must assign a value
you must provide a value to a static final member of the class when it is defi ned.
Can you do the following?
public class Canine {
public double getAverageWeight() {
return 50;
}
}
public class Wolf extends Canine {
public double getAverageWeight() {
return super.getAverageWeight()+20;
}
public static void main(String[] args) {
System.out.println(new Canine().getAverageWeight());
System.out.println(new Wolf().getAverageWeight());
}
}
public class BactrianCamel extends Camel {
private int getNumberOfHumps() {
return 2;
}
}
Yes because only public and protected methods are visible.
What is static method hiding?
A hidden method occurs when a child class defines a static method with the same name
and signature as a static method defined in a parent class.
Make a default method code ;
public default void hello(){
System.out.println(“Some implementation”);
}
What are the rules for method hiding?
- The method in the child class must have the same signature as the method in the parent
class. - The method in the child class must be at least as accessible or more accessible than the
method in the parent class. - The method in the child class may not throw a checked exception that is new or
broader than the class of any exception thrown in the parent class method. - If the method returns a value, it must be the same or a subclass of the method in the
parent class, known as covariant return types. - The method defined in the child class must be marked as static if it is marked as
static in the parent class (method hiding). Likewise, the method must not be marked
as static in t
All the methods of an interface has what access modifier?
public
public class Bear {
public static void sneeze() {
System.out.println(“Bear is sneezing”);
}
public void hibernate() {
System.out.println(“Bear is hibernating”);
}
}
public class Panda extends Bear {
public void sneeze() {
System.out.println(“Panda bear sneezes quietly”);
}
public static void hibernate() {
System.out.println(“Panda bear is going to sleep”);
}
}
does not compile because the child class is not method hiding correctly.
If the sneeze is static, the child method needs to be static as well.
Difference between method hiding and method overriding?
Method hiding is static and method overriding is non-static
Will this work?
public class Bird {
public final boolean hasFeathers() {
return true;
}
}
public class Penguin extends Bird {
public final boolean hasFeathers() {
return false;
}
}
no you cannot override final methods
Does Java allow variable overriding? Important
No.Java doesn’t allow variables to be overridden but instead hidden
What is polymorphism?
polymorphism -the property of an object to take on many different forms
Can you do the following?
public class nilimaAssessment implements LuckyInterview extends Hardwork{
}
No
public class nilimaAssessment extends Hardwork implements LuckyInterview{
}
Make an upcast
public class Parent(){
}
public class Kid(){
}
public class Main(){
public static void main(String[] args){
Parent a = new Kid();
}
}
Make a downcast
Parent MrWilson = new Kid();
Kid alisson = (Kid) MrWilson;
Parent MsWong = new Kid();
Kid Jimmy = (Kid) MsWong;
Can you do the following?
Object o = new Object();
String s = (String) o;
No, gives you CLassCast Exception.
Will compile
// this will fail at runtime, because o doesn’t reference a String
What is a virtual method?
A virtual method is a method in which the specific implementation is not determined until the runtime.
Give examples of virtual methods? Why?
non-final, non-static and non-private Java methods.
They can be overridden at runtime.
What is polymorphic parameters?
The ability to pass instances of a subclass or interface to a method
a method that takes a parameter with type java.lang.Object
A method that takes a parameter with type java.lang.Object will take any reference.
Including NULL
Both abstract and interfaces can be extended with what?
Both abstract
classes and interfaces can be extended with the extends keyword
Where can static method be contained?
Both
abstract classes and interfaces can contain static method
Where can default method be created?
Only interfaces.
Can concrete class implement what?
A concrete class must implement all inherited abstract methods.
(Remember not interfaces)
When should i consider using abstract classes?
Consider using abstract classes if any of these statements apply to your situation:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
UML interface. A implements B
A extends B
<<interface>> ------/> SuperClass \_\_\_\_\_\_\_\_\_/> sometimes interfaces are also circles
Can you make an abstract class the following?
public
default
protected
private
public = yes
default = yes
protected = no
private= no
Methods in interfaces can be static?
yes.
Methods in interfaces can be protected
no
Interfaces methods are implicitly
public and abstract
Can you call a static method using a reference variable?
NO you need to use the Interfacename.staticmethodname();
nterface Jumpable{ int Min=10; } interface Move{ String Min="has cancer"; } public class Aa implements Jumpable, Move{ Aa(){ System.out.println(Min); } }
wont compile
```
interface PunchableFace{ void min();
}
class CEO implements Punc{void min();}
DNC bc interface methods are public and you can trying to make it default.
if you do default void min();
Can an interface define contructor?
No
Are static method ever inherited?
No
interface Jumpable{ int Min=10; } interface Move{ String Min="20"; } public class Aa implements Jumpable, Move{ }
will compile
interface Jumpable{ int Min=10; } interface Move{ String Min="cancer"; } public class Aa implements Jumpable, Move{ Aa(){ System.out.println(Min); } }
will not compile. Min is amb
interface Jumpable{ abstract String c(); } interface Move{ abstract String c(); } public class Aa implements Jumpable, Move{ @Override public String c() { // TODO Auto-generated method stub return null; } }
Yes
interface Jumpable{ abstract String c(); } interface Move{ abstract void c(); } public class Aa implements Jumpable, Move{ @Override public String c() { return "C"; } }
dnc
*
Name all the method that can be defined in interface
abstract, default and static
Can you override default methods from an interface by a normal class?
no. only if thedefault return OBject and the subclass has lower or same
What happens when you modify static method to default/abstract?
the code that calls the method wont compile.
What happens when you modify abstract method to default/static?
abstract to default - continue to compile
abstract method to static. wont
What happens from default to abstract? Static?
default to abstract - no
default to static - no
public interface H{ public int eatPlats(); } public interface O{ public void eatPlants(); } public class Bear implements H, O{ public int eatPlants(){ sysout("Eating":10); return 10; } public void eatPlants(){ sysout("Eating"); } }
DNC, return types are different.
public interface H{ public int eatPlats(); } public interface O{ public void eatPlants(); } public interface Bear extends H, O } public abstract class Tiger implments O{}
DNC
Can you make the interface variable private, protected or abstract?
no it can only be public static final
interface A{
abstract int I();
}
class Manager implements A{
int I(){
return 1;
}
}
if there is abstract, the concrete must do public.
public interface H{ static void eatPlats(); } public interface O{ static int eatPlants(); } public interface Bear extends H, O }
if static no problem.
interface Re{
void move();
}
class I implements Re{
void move();
}
default method override. DNC
make move public to compile