Chapter 7 - Beyond Classes Flashcards

(59 cards)

1
Q

Declaring interface

abstract interface CanBarrow{

public abstract float getSpeed(int age);

public static final int MAX=25;

}

A

All interfaces are implicitly abstract modifier at top level

all methods implicitly have public abstract modifiers

All variables are implicitly constants having public static final

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

Can interface extends multiple interfaces at the same time?

public interface HasBigEyes extends Nocturnal, CanFly{}

A

Yes

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

When a class implements 2 interfaces that have exact abstract method signatures?

A

Allowed

Implementing class would have to provide a compatible concrete method

If both abstract method declarations in interfaces has similar method signatures but incompatible then Java throws compiler error

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

Are these valid in interface ?

protected void canFly();
private int count=5;

A

No

Modifiers explicitly declared should not conflict with implicitly assumed modifiers

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

Special interface methods

A

default
private
static
private static

I think you can guess what they mean😀
Can you guess their implicitly added modifiers?

default - public
private - n/a
static - public
private static - n/a

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

interface default method rules

Note: these are instance related methods

A

Can not be abstract, final or static

If a class inherits two or more default methods with same signature then class must override the method

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

How to call interface default method when concrete class overrides it

A

<interfacename>.super.<method>

Example:

Walk.super.getSpeed();

This is where default method exhibits static properties but it’s not quite the same. We use interface name first followed by super operator to indicate we are not using class inheritance but using instance inheritance
</method></interfacename>

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

interface static method rules other than obvious rules

A

1) can not be abstract or final
2) not inherited into implementing class. You have to use interface name to access it

Note: if not coded implicit access modifier is public. It can have explicit modifier private

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

interface private method

A

This is the only method that looks exactly like a regular concrete method in an interface.

This is used by other private methods only

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

interface private static method

A

Like its name this is a static method available to be used only with in interfaces. Typically used by other private or private static method

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

enum built in methods?

A

values() - gives an array of all enums constants

ordinal() - integer of index of the constant

valueOf(String)- takes string and returns enum value

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

Can enum implement an interface?
Can enum extend another class?

A

Yes
No

It can but it doesn’t extend a class

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

Enum constructor access modifiers

A

private (implicit)

This is only valid when enum is initialized by JVM. We don’t call enum constructor to create an enum constant. We only use it.

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

Enum initializing

A

First time an enum is used JVM calls all constructors in enum and create enum values all together before it’s used in program

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

How do you call enum instance method

A

Seasons.SUMMER.printVisitors();

Or
Season s=Season.SUMMER;
s.printVisitors();

The instance methods declared should be public

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

Can we create enum methods different for each constant

A

Yes

public enum SeasonWithTimes{

WINTER {
public String getHours() { return 10am-3pm; }
},

SUMMER{
public String getHours() { return 9-7pm; }
};

public abstract String getHours();

}

This enum looks like an abstract class . This enum has an abstract method. So each enum value must implement the method. Else Java issues compiler error

Important note: instead of declaring an abstract method we can provide a common method implementation and enum value can choose to override like in above example

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

What can an enum has?

A

Implement an interface
Have constructors (private)
Have final variable (private)
Have final static variables (private)
Have enum methods (public)

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

Sealed class syntax

A

public sealed class Bear permits Kodiak, Panda {}

sealed keyword with permits keyword defines wha subclasses are allowed to extend the current class

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

non-sealed keyword

A

Indicates a class that extends sealed classes, can be extended by unspecified classes

If you don’t want the class to be extended by any other classes, just use fina keyword

If you want a specific class to extend this subclass use sealed keyword agian on this subclass with permits keyword indicating next level subclasses . Chaining

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

Does sealed and subclasses need to be in same package?

A

Yes

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

Subclass that extends sealed classes to have certain modifiers?

A

Yes

Should be one of these 3

sealed - indicating another set of subclasses. Gaining

non-sealed - meaning any class can extend it further

final - this subclass can’t be extended anymore

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

An example of sealed subclass extending sealed classes

A

public sealed class ClownFish extends Fish permits OrangeClownFish{}

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

Is permits keyword required on a sealed class definition

A

No

Not required as long as both sealed and subclasses are declared with in single .java file

permits keyword can be omitted if the subclasses are nested

public sealed class Snake{
final class Cobra extends Snake {}
}

See the attached image

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

Nested subclass extending a sealed classes. What if we want to use permits keyword even though it’s not required

A

Use namespace qualifiers

Since subclass requires a reference to the sealed classes namespace

25
Sealing interfaces
They can permit classes that can implement sealed interface. They can permit interfaces that extends sealed interface. Can include both at same time public sealed interface Swims permits Duck, Floats {} public final class Duck implements Swims {} public non-sealed interface Floats extends Swims {}
26
Modifiers for interfaces that extend a sealed interface
While class can have 3 modifiers (final, sealed, non-sealed) interfaces can have only 2 such as sealed and non-sealed. Interface can not be marked as final
27
Pattern matching with sealed classes
Since sealed classes can only be extended by certain subclasses, pattern matching is allowed and possible to be used . abstract sealed class Fish permits Trout, Bass {} public String getType(Fish fish) { return switch(fish) { case Trout t -> t.type; case Bass b -> “bass”; }; } Note: if Fish is not abstract then switch clause should include case with Fish or default clause
28
Sealed class rules
1) sealed classes declared with sealed and permits keywords 2) sealed classes must be declared in the same package or named module as their direct subclasses 3) direct subclasses of sealed classes must be marked final, sealed or non-sealed. For interfaces that extend a sealed interface, only sealed and non-sealed modifiers are permitted 4) the permits clause is optional if the sealed class and its direct subclasses are declared within the same file or the subclasses are nested with in the sealed class 5) interfaces can be sealed to limit the classes that implement them or the interfaces that extend them allowing pattern matching to be used widely in switch expressions
29
Java record type
A record is a special type of data oriented class in which compiler inserts boilerplate code such as getters only public record Crane(int eggs, String name) {} var mommy = new Crane(4, “Cammy”); print(mommy.eggs()); print(mommy.mame()); Please note getter method names are exactly same as field names.
30
Members automatically added to records
Constructor Accessor methods for each field equals() hashcode() - based on fields toString()
31
Is this valid public record Crane() {}
Yes
32
Does this compile? public record Crane(int eggs, String name) { public Crane(int eggs, String name) {} }
No When explicit long constructor is used, we need to assign the record fields with passed fields such as below public record Crane(int eggs, String name) { public Crane(int eggs, String name) { this.eggs=eggs; this.name=name; } }
33
What is a long constructor of record type?
Sets all fields like a regular class constructor public record Crane(int eggs, String name) { public Crane(int eggs, String name) { this.eggs=eggs; this.name=name; } }
34
What is a compact constructor in record types?
Used for selective fields. Other fields not referenced are implicitly set. Please note this is a special type of constructor that doesn’t take any parameters since it doesn’t have parentheses public record Crane(int eggs, String name) { public Crane { name=name.toUppercase(); } } Note: we didn’t reference this operator since we are not passing local method parameters. They are all implicitly set and allows the program to manipulate after they are set
35
What is the output? public record Crane(int eggs, String name) { public Crane{ this.eggs=23; } } var c = new Crane(10, “Ammu”); print(c.eggs());
Doesn’t compile Since this operator is used in a compact constructor. Remove it then it will print 23
36
Overloaded constructor in record type
It’s allowed to have a constructor with different method parameters but the first line of overloaded constructor should call this() long constructor and pass values manipulated. After this() any statement don’t have an impact on fields. Note: this operator {this.} is prohibited in compact and overloaded constructor but allowed in long constructor
37
Can record implement an interface?
Yes
38
Can a record has static fields?
Yes public record Crane(int eggs, String name) { private static int counter=0; public Crane(String name) { this( counter++, name); } }
39
Are these record pattern matching valid? record Crane(int eggs, String name) {} if(bird instanceof Crane crane) {} if(bird instanceof Crane(int a, String str) crane) {} if(bird instanceof Crane(long a, String str)) {} if(bird instanceof Crane(int a, Object str)) {}
1) compiles fine. crane is pattern variable 2) doesn’t compile. Both field pattern declarations and object pattern variable are not allowed. Only one of them 3) doesn’t compile. Numeric promotion not allowed 4) compiles fine. Object is compatible with String
40
Nesting record pattern matching record Bear (String name, String favorite) {} record Couple (Bear a, Bear b) {} What are the various ways of us g pattern matching var c= new Couple(new Bear(“Ammu”, “dosa”), new Bear(“Addu”, “punugulu”));
c instanceof Couple(Bear a, Bear b) c instanceof Couple(Bear(String n, String f), Bear b) c instanceof Couple(Bear(String a, String b), Bear(String p, String q)) Note: in the last one make sure the pattern field variables are unique. If not JVM throws compiler error
41
Does this compile ? record Bear (String name, String favorite) {} record Couple (Bear a, Bear b) {} var c= new Couple(new Bear(“Ammu”, “dosa”), new Bear(“Addu”, “punugulu”)); c instanceof Couple(Bear(String a, String b), Bear(String a, String q))
No String a in both Bear conflicts
42
Matching records with var and generics
Yes possible as long as pattern variable names don’t conflict
43
Does this compile ? record Bear (String name, List favorites) {} record Couple (Bear a, Bear b) {} var c= new Couple(new Bear(“Ammu”, List.of(“dosa”)), new Bear(“Addu”, List.of(“punugulu”))); if(c instanceof Couple(Bear(var n, List f), var b) && f.getFirst().toLowerCase().contains(“p”)) {}
Doesn’t compile The reference type of f is List not List. So f.getFirst() returns an Object on which you can’t call toLowerCase()
44
Applying pattern matching records to switch statement record Snake(Object o) {} long showData(Snake s){ return switch(s){ case Snake(Long l) -> l + 1; case Snake(Integer i) -> i + 12; case Snake(Number n) -> n.intValue()+ 100; case Snake(Object o) -> 1; } } print(showData(new Snake(1))); print(showData(new Snake(2L))); print(showData(new Snake(3.0)));
13 3 103
45
Customizing records It can override getter methods It can have static fields It can have static initializers It can’t have instance fields and instance initializers. It defeats the whole purpose of record
46
What are the different types of nested classes
Inner class Static nested class Local class Anonymous class
47
Can inner class access members of the outer class including private members?
Yes
48
How to instantiate an inner class from outside of outer class or from static method
You create outer object and then use new operator (new Ouer).new Inner(); In other words var home=new Home(); var room=home.new Room();
49
How to reference outer class variables in inner class when the variables names are matching
A has B has C and all have x variable inside as member x or this.x -> C class member B.this.x -> B class member A.this.x -> A class member How do you instantiate A a = new A(); A.B b = a.new B(); A.B.C c = b.new C(); Its commmon to instantiate inner class in an instance method of outer class in which case above is not necessary
50
Anonymous class
An anonymous class is a specialized form of an inner class that doesn’t not have a name. It’s declared and instantiated all in one statement t using the new keyword, type name with parentheses and a set of braces {} An anonymous class must extend an existing class or implement an existing interface. It can be declared with in method or as an instance member abstract class Sale{ abstract int dollarsOff(); } Logic: Sale sale=new Sale(){ private int count =4; int dollarsOff(){ return count*3; } }; // don’t forget the semi colon
51
Static nested class?
It’s a static type defined at the member level. Unlike inner class a static nested class can be instantiated without an instance of the enclosing class. Outer class can access static class variables even if they are private
52
Are nested records static?
Yes they are implicitly static Meaning it can be used without a reference to the outer class
53
Local classes properties
1) Do not have an access modifier 2) can be declared final or abstract 3) can include instance and static members 4) have access to all fields and methods of the enclosing class when defined in an instance method 5) can access final and effectively final local variables
54
What is the output ? public class Home{ private int length=5; private int findVolume(){ private final int width=12; int height=2; int count=2; Class VolumeCalculator{ public int multiply(){ return length * width * height * cnt; } } var cal=new VolumeCalculator(); int vol=cal.multiply(); count=4; } }
Doesn’t compile Though inner local class can access outer class member length and local final variable width and effectively final variable height, it can not use count which is not an effectively final variable. Though count is used after calling the method it’s still recognized as not effectively final violating the rule
55
Casting to interfaces types. Note: Dog is an interface Wolf implements Canine Wolf wolf=new Wolf(); Dog dog=(Dog) wolf;
Compiles fine But throws runtime exception ClassCastException BUT Imagine if Dog is a final class Then Java knows casting to Dog interface is invalid. It knows there is no possible subclass that could implement Dog interface
56
Ben a method is overridden how do you still call parent class method if you want to?
using super operator The super operator can be called from subclass to refer to overridden method from super class super.getHeight() When this is called from subclass it calls parent class version of the method.
57
Is this valid? public final record Animal(){}
Yes A record can be empty A record is implicitly final as there is no such thing as extending another record though it can implement interfaces
58
Is this valid? public abstract record Animal(){}
No A record can not be abstract as there is no such thing as extending another record though it can implement interfaces
59
Are nested records inherently static?
Yes Nested record methods being static ca not access enclosing class instance variables