Inheritance Flashcards

1
Q

class Dog extends Animal

A

Dog -is a subclass of class Animal
*A subclass can ALWAYS be assigned to a super class variable without any cast. It will always compile and run without any exception.
* but an Animal is not always a DOG, that is way for the reverse you need a CAST for it to compile
* and if at runtime the actual obj referenced by Animal is not a Dog then a ClassCastException will be thrown

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

C1 and C2 extends B1
B1 and B2 Extends A
Assume that method public void m1(){ … } is defined in all of these classes EXCEPT B1 and C1.

A

*C1 will inherit B1’s m1() which in turn inherits m1() from A.
*C2 has m1(), so its m1() will override A’s m1().

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

What You Can Do in a Subclass

A

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:

The inherited fields can be used directly, just like any other fields.
You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
You can declare new fields in the subclass that are not in the superclass.
The inherited methods can be used directly as they are.
You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
You can declare new methods in the subclass that are not in the superclass.
You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.

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

Private Members in a Superclass

A

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

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

Casting Objects

A

You can assign a subclass object reference to superclass reference without a cast but to assign a super class object reference to a subclass (or interface) reference you need an explicit cast !!!!!!!!!!
Superclass a = Subclass b;
Subclass b =(SubClass) Superclass a;

Implicit casting:
Object obj = new MountainBike();

Explicit casting:
MountainBike myBike = (MountainBike)obj;
–>This cast inserts a runtime check that obj is assigned a MountainBike so that the compiler can safely assume that obj is a MountainBike. If obj is not a MountainBike at runtime, an exception will be thrown.You can make a logical test as to the type of a particular object using the instanceof operator. This can save you from a runtime error owing to an improper cast

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

Multiple Inheritance of State, Implementation, and Type

A

1.NOT ALLOWED in java : Multiple inheritance of state –> ability to inherit fields from multiple classes (I guess because when an object will inherit fields from all of the class’s superclasses, it is ambiguous what methods or constructor to use to instantiate/modify the state/ the fields??? )

2.Multiple inheritance of implementation–> the ability to inherit method definitions from multiple classes with DEFAULT METHODS!!!!!!!!!
Problems arise with this type of multiple inheritance, such as name conflicts and ambiguity. The Java compiler provides some rules to determine which default method a particular class uses:

**Instance methods are preferred over interface default methods!!!!
**If two or more independently defined default methods conflict, or a default method conflicts with an abstract method, then the Java compiler produces a compiler error. You must explicitly override the supertype methods.ou could invoke any of the of the default implementations with the super keyword.
**Methods that are already overridden by other candidates are ignored. This circumstance can arise when supertypes share a common ancestor.
EG: the overring method has precedence!
public interface Animal {
default public String identifyMyself() {
return “I am an animal.”;
}
}
public interface EggLayer extends Animal {
default public String identifyMyself() {
return “I am able to lay eggs.”;
}
}
public interface FireBreather extends Animal { }
public class Dragon implements EggLayer, FireBreather {
public static void main (String… args) {
Dragon myApp = new Dragon();
System.out.println(myApp.identifyMyself());
}
}

The method Dragon.identifyMyself returns the string I am able to lay eggs.
3.Multiple inheritance of type–> the ability of a class to IMPLEMENT more than one INTERFACE.
An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements. This means that if a variable is declared to be the type of an interface, then its value can reference any object that is instantiated from any class that implements the interface. a class can inherit different implementations of a method defined (as default or static) in the interfaces that it extends. In this case, the compiler or the user must decide which one to use.???????

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

STATIC Methods in interfaces

A

The idea behind static interface methods is to provide a simple mechanism that allows us to increase the degree of cohesion of a design by putting together related methods in one single place without having to create an object.

The same can pretty much be done with abstract classes. The main difference is that abstract classes can have constructors, state, and behavior.

Furthermore, static methods in interfaces make it possible to group related utility methods, without having to create artificial utility classes that are simply placeholders for static methods.

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

Overriding and Hiding Methods

A

Static methods and fileds(static or non-static ) are never overridden –> they are hidden!!!!!!!!!!!!!!

An INSTANCE method in a subclass with the SAME SIGNATURE(name, plus the number, the order? and the type of its parameters) and return type(or a subtype=covariant) 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:

The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
EG:
class A{
int i = 10;
public static void m1(){ }
public void m2() { }
}
class B extends A{
int i = 20;
public static void m1() { }
public void m2() { }
}
Here, UNLIKE m2, m1() of B does not override m1() of A, it just hides m1() of A, as proven by the following code:
A a = new B();
System.out.println(a.i) //will print 10 instead of 20
a.m1(); //will call A’s m1
a.m2(); //will call B’s m2 as m2() is not static and so overrides A’s m2()

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

Note: Static methods in interfaces are never inherited.

A

whaaaat???

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

Modifiers

A

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

You will get a compile-time error if you attempt to change an instance method in the superclass to a static method in the subclass, and vice versa.

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

Defining a Method with the Same Signature as a Superclass’s Method

A

Defining a Method with the Same Signature as a Superclass’s Method
A subclass INSTANCE methods
–>overrides a superclass instance method
–> generated copile time error for a Superclass static methods
A subclass STATIC methods
–>generated compile-time error for a superclass instance method
–> hides a Superclass static methods

EG:
void methodA(){
System.out.println(“base - MethodA”);
}
}

class Sub extends Base{
public void methodA(){
System.out.println(“sub - MethodA”);
}
public void methodB(){
System.out.println(“sub - MethodB”);
}
public static void main(String args[]){
Base b=new Sub(); //1
b.methodA(); //2
b.methodB(); //3
}
}
–> genereated Compile time error at //3 because methodB() is not defined in Base.
The point to understand here is, b is declared to be a reference of class Base and methodB() is not defined in Base. So the compiler cannot accept the statement b.methodB() because it only verifies the validity of a call by looking at the declared class of the reference.
For example, the compiler is able to verify that b.methodA() is a valid call because class Base has method methodA. But it does not “bind” the call. Call binding is done at runtime by the jvm and the jvm looks for the actual class of object referenced by the variable before invoking the method.

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

Overloading

A

In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.

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

Polymorphism

A

The JVM calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable’s type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.

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

Hiding Fields

A

NOT recommended.
Within a class, a field that has the same name as a field in the superclass hides the superclass’s field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super,

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

Super keyword

A

Invocation of a superclass constructor must be the first line in the subclass constructor.
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

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

The methods of the Object Superclass

A

You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class!!
**clone()–> If a class, or one of its superclasses, implements the Cloneable interface, you can use the clone() method to create a copy from an existing object. otherwise the method throws a CloneNotSupportedException exception. For some classes, the default behavior of Object’s clone() method works just fine. If, however, an object contains a reference to an external object, say ObjExternal, you may need to override clone() to get correct behavior. Otherwise, a change in ObjExternal made by one object will be visible in its clone also. This means that the original object and its clone are not independent—to decouple them, you must override clone() so that it clones the object and ObjExternal. Then the original object references ObjExternal and the clone references a clone of ObjExternal, so that the object and its clone are truly independent.
**equals()–> ses the identity operator (==) to determine whether two objects are equal.. It ok for primitives but it for obj it tests whether the object references are equal(==).You should always override the equals() method if the identity operator is not appropriate for your class.If you override equals(), you must override hashCode() as well.
** finalize()–> may be invoked on an object when it becomes garbage.
**getClass() method returns a Class object, which has methods you can use to get information about the class(getName, getMethods, getSuperclass, getInterfaces)
**hashcode()–> an integer value generated by a hashing algorithm. If two objects are equal, their hash code must also be equal.
**toString()–>Should always be overrided

17
Q

FINAL keyword

A

final METHODS–> can not be overridden!!
You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object.

final CLASS –> cannot be subclassed.
This is particularly useful, for example, when creating an immutable class like the String class.

18
Q

Abstract Methods and Classes

A

abstract class –>Abstract classes CANNOT be INSTANTIATED, but they can be subclassed.!!!!! If a class includes abstract methods, then the class itself must be declared abstract, but an abstract class may or may not include abstract methods. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

abstract method –> WIHTOUT BODY- is a method that is declared without an implementation (without braces, and followed by a semicolon)

**An abstract class does NOT need to implement all of the interface’s methods.

19
Q

Abstract classes vs Interfaces

A

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

Which should you use, abstract classes or interfaces?

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.
Consider using interfaces if any of these statements apply to your situation:
You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.

20
Q

Inheritance

A

Except for the Object class, a class has exactly one direct superclass. A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits.

21
Q

inheriting exceptions

A

** If the superclass method does NOT declare an exception, subclass overridden method CANNOT declare the checked exception but it can declare unchecked exception.
**If the superclass method declares an exception, subclass overridden method can declare SAME, SUBCLASS exception or NO exception but cannot declare parent exception.

22
Q

Initialisation Order

A

As per Section 12.4.1 given here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

T is a class and an instance of T is created.

T is a class and a static method declared by T is invoked.

A static field declared by T is assigned.

A static field declared by T is used and the field is not a constant variable (§4.12.4).

T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization.

A class or interface will not be initialized under any other circumstance.

23
Q

Inheriting multiple memebers from multiple interfaces

A

Having ambiguous fields or methods does not cause any problems by itself but referring to such fields/methods in an ambiguous way will cause a compile time error.!!!!
EG:
class TestClass implements T1, T2{
public void m1(){}
}
interface T1{
int VALUE = 1;
void m1();
}
interface T2{
int VALUE = 2;
void m1();
}

Valid if:
TestClass tc = new TestClass();
System.out.println(( ( T1) tc).VALUE);
However, explicit cast is not required for calling the method m1() : ( ( T2) tc).m1();
tc.m1() is also fine because even though m1() is declared in both the interfaces, the definition to both resolves unambiguously to only one m1(), which is defined in TestClass.

24
Q

Constructors

A

The compiler will insert a default(a no args) constructor if no constructor exists in the class!!!!!

The compiler will also insert on the first line in the constructor of a subclass need to be a call to a supercalss construcotr with the SUPER() keyword or a call the another constructor of the subclass with the THIS keyword. If not supplies

Subclass(){
super();
} –> IT WILL NOT COMPILE IF THE SUPERCLASS DOES NOT HAVE A No-args constructor
–> but only if you don’t explicitly call either any super class constructor using super(…) or another constructor of the same class using this

But if a class has at least one constructor with parameters, the compiler will not insert a no args constructor!!!!!!!!!!!!!!!!!!!!!

Calling super(Superclass member field) – >will not compile because it cannot be used by a subclass until super class’s constructor has executed