Enums, Nested Classes, Interface Members

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

Private methods cannot be overridden in subclasses. Only methods that are inherited can be overridden and private methods are not inherited. An overriding method can declare that it throws a wider spectrum of checked exceptions than the method it is overriding. The overriding method may opt not to declare any throws clause even if the original method has a throws clause. No exception (i.e. an empty set of exceptions) is a valid subset of the set of exceptions thrown by the original method so an overriding method can choose to not have any throws clause. ...

A method can be overridden by defining a method with the same signature(i.e. name and parameter list) and return type as the method in a superclass. The return type can also be a subclass of the original method's return type. A subclass may have a static method with the same signature as a static method in the base class but it is not called overriding. It is called hiding because the concept of polymorphism doesn't apply to static members.

4 Tipos de classes internas

Inner class: A non‐ static type defined at the member level of a class Static nested class: A static type defined at the member level of a class Local class: A class defined within a method body Anonymous class: A special case of a local class that does not have a name

public class Enclosing { static class Nested { private int price = 6; } public static void main(String[] args) { Nested nested = new Nested(); System.out.println(nested.price); } } ...

Since the class is static, you do not need an instance of Enclosing to use it. You are allowed to access private instance variables

//in file Pets.javaenum Pets{ String name; DOG("D"), CAT("C"), FISH("F"); Pets(String s) { name = s;}} Enum constants (here, DOG, CAT, and FISH) must be declared before anything else. Therefore, String name; is invalid here. ...

//in file Pets.javaenum Pets{ String name; DOG("D"), CAT("C"), FISH("F"); public Pets(String s) { name = s;}} An enum constructor is always implicitly private. You cannot make it public or protected.

DEFAULT INTERFACE METHOD DEFINITION RULES 1. A default method may be declared only within an interface. 2. A default method must be marked with the default keyword and include a method body. 3. A default method is assumed to be public ....

4. A default method cannot be marked abstract, final, or static. 5. A default method may be overridden by a class that implements the interface. 6. If a class inherits two or more default methods with the same method signature, then the class must override the method.

ANONYMOUS CLASS It is declared and instantiated all in one statement using the new keyword, a type name with parentheses, and a set of braces {}. Anonymous classes are required to extend an existing class or implement an existing interface. They are useful when you have a short implementation that will not be used anywhere else. SaleTodayOnly sale = new SaleTodayOnly() { int dollarsOff() { return 3; } }; // Don't forget the semicolon! ...

But what if we want to implement both an interface and extend a class? You can't with an anonymous class, unless the class to extends is java.lang.Object. Pode ter uma classe anonima no argumento do metodo return admission(5, new SaleTodayOnly() { public int dollarsOff() { return 3; } });

An inner class, also called a member inner class, is a non‐static type defined at the member level of a class (the same level as the methods, instance variables, and constructors). Inner classes have the following properties: ...

Can be declared public, protected, package‐private (default), or private Can extend any class and implement interfaces Can be marked abstract or final Cannot declare static fields or methods, except for static final fields Can access members of the outer class including private members

CREATING SIMPLE ENUMS public enum Season { WINTER, SPRING, SUMMER, FALL } ...

Enum values are considered constants and are commonly written using snake case, often stylized as snake_case. This style uses an underscore ( _) to separate words with constant values commonly written in all uppercase. ex: VANILLA, ROCKY_ROAD, MINT_CHOCOLATE_CHIP

public enum Season { WINTER { public String getHours() { return "10am-3pm"; } }, SPRING { public String getHours() { return "9am-5pm"; } }, SUMMER { public String getHours() { return "9am-7pm"; } }, FALL { public String getHours() { return "9am-5pm"; } }; public abstract String getHours(); } ...

Every enum value is required to implement this method. If we forget to implement the method for one of the values, then we get a compiler error. The enum constant WINTER must implement the abstract method getHours() If we don't want each and every enum value to have a method, we can create a default implementation and override it only for the special cases. public enum Season { WINTER { public String getHours() { return "10am-3pm"; } }, SUMMER { public String getHours() { return "9am-7pm"; } }, SPRING, FALL; public String getHours() { return "9am-5pm"; } }

Season summer = Season.SUMMER; switch (summer) { case WINTER: System.out.println("Get out the sled!"); break; case SUMMER: System.out.println("Time for the pool!"); break; default: System.out.println("Is it summer yet?"); } ...

Java treats the enum type as implicit. In fact, if you were to type case Season.WINTER, it would not compile.

DEFAULT METHODS A default method may be overridden by a class implementing the interface. The name default comes from the concept that it is viewed as an abstract interface method with a default implementation. A default method allows you to add a new method to an existing interface, without the need to modify older code that implements the interface. the Comparator interface includes a default reversed() method that returns a new Comparator in the order reversed ...

Note that the default interface method modifier is not the same as the default label used in switch statements. Likewise, although package‐private access is commonly referred to as default access, that feature is implemented by omitting an access modifier. They also cannot be marked as final, because they can always be overridden in classes implementing the interface. Finally, they cannot be marked static since they are associated with the instance of the class implementing the interface. Like abstract interface methods, default methods are implicitly public.

Which variable (or static method) will be used depends on the class that the variable is declared of. Which instance method will be used depends on the actual class of the object that is referenced by the variable. ...

So, in line o1.m1(), the actual class of the object is C, so C's m1() will be used. So it returns 30.In line o2.i, o2 is declared to be of class B, so B's i is used. So it returns 20.

public class PrintNumbers { private int length = 5; public void calculate() { final int width = 20; class MyLocalClass { public void multiply() { System.out.print(length * width); } } MyLocalClass local = new MyLocalClass(); local.multiply(); } public static void main(String[] args) { PrintNumbers outer = new PrintNumbers(); outer.calculate(); } } ...

The compiler is generating a .class file from your local class. A separate class has no way to refer to local variables. If the local variable is final, Java can handle it by passing it to the constructor of the local class or by storing it in the .class file.

switch (summer) { case Season.FALL: // DOES NOT COMPILE System.out.println("Rake some leaves!"); break; case 0: // DOES NOT COMPILE System.out.println("Get out the sled!"); break; } ...

The first case statement does not compile because Season is used in the case value. If we changed Season.FALL to just FALL, then the line would compile. we said that you can't compare enums with int values, you cannot use them in a switch statement with int values either.

public interface Carnivore { public default void eatMeat(); // DOES NOT COMPILE public int getRequiredFoodAmount() { // DOES NOT COMPILE return 13; } } ...

The first method, eatMeat(), doesn't compile because it is marked as default but doesn't provide a method body. The second method, getRequiredFoodAmount(), also doesn't compile because it provides a method body but is not marked with the default keyword.

Records You can define a top level record i.e. directly under a package, a nested member record class i.e. within a class/interface, or a local record i.e. within a method. A nested record class is implicitly static. That is, every member record class and local record class is static. It is permitted for the declaration of a member record class to redundantly specify the static modifier, but it is not permitted for the declaration of a local record class. A record class is implicitly final. It is permitted for the declaration of a record class to redundantly specify the final modifier. Records cannot be marked abstract, sealed, or non-sealed. The direct superclass type of a record class is Record. Thus, a record cannot have an extends clause and so it cannot extend any other class.

The serialization mechanism treats instances of a record class differently than ordinary serializable or externalizable objects. In particular, a record object is deserialized using the canonical constructor. But there are some restrictions as well: It cannot contain an instance field declaration (static fields are allowed). It cannot have an instance initializer (static initializers are allowed). It cannot have abstract or native methods.

A local class is a nested class defined within a method. Like local variables, a local class declaration does not exist until the method is invoked, and it goes out of scope when the method returns. Those instances can still be returned from the method They can be declared inside constructors and initializers too. ...

They do not have an access modifier. They cannot be declared static and cannot declare static fields or methods, except for static final fields. They have access to all fields and methods of the enclosing class (when defined in an instance method). They can access local variables if the variables are final or effectively final.

enum Pets{ DOG("D"), CAT("C"), FISH("F"); static String prefix = "I am "; String name; Pets(String s) { name = prefix + s; } public String getData(){ return name; } } ...

Unlike a regular java class, you cannot access a non-final static field from an enum's constructor.

An enum provides a values() method to get an array of all of the values. You can use this like any normal array, including in an enhanced for loop, often called a for‐each loop. for(Season season: Season.values()) { System.out.println(season.name() + " " + season.ordinal()); } ...

WINTER 0 SPRING 1 SUMMER 2 FALL 3 The int value will remain the same during your program, but the program is easier to read if you stick to the human‐readable enum value. You can't compare an int and enum value directly anyway since an enum is a type, like a Java class, and not a primitive int. if ( Season.SUMMER == 2) {} // DOES NOT COMPILE

sealed interface Cacheable permits Value, Result{ default void clear(){ System.out.println("clearing cache..."); } } Which of the following definition will compile without error? non-sealed interface Value extends Cacheable{ } OK non-sealed interface Result extends Cacheable{ } OK sealed interface Value extends Cacheable{ } FALSE sealed interface Result extends Cacheable{ } FALSE A sealed interface must have a permits clause. ....

interface Value extends Cacheable{ } FALSE interface Result extends Cacheable{ } FALSE A permitted subinterface must be declared sealed or non-sealed (i.e. exactly one of these two). Note that a permitted subclass may also be declared final (instead of sealed or non-sealed) but since an interface cannot be made final, a permitted subinterface cannot be declared final

Note the difference between an inner class and a static nested class. Remember: 1) A nested class is any class whose declaration occurs within the body of another class or interface. 2) A top level class is a class that is not a nested class. 3) An inner class is a nested class that is not explicitly or implicitly declared static. 4) A class defined inside an interface is implicitly static. ...

public class A // outer class { static public class B //static nested class. //It can be used in other places: A.B b = new A.B(); There is no outer instance. { } class C //Inner class. It can only be used like this: // A.C c = new A().new C(); Outer instance is needed. { } }

public interface Hop { static int getJumpHeight() { return 8; }} public class Bunny implements Hop { public void printDetails() { System.out.println(getJumpHeight()); // DOES NOT COMPILE Without an explicit reference to the name of the interface, the code will not compile ...

public class Bunny implements Hop { public void printDetails() { System.out.println(Hop.getJumpHeight()); } } Java "solved" the multiple inheritance problem of static Interface methods by not allowing them to be inherited. Class that implements two interfaces containing static methods with the same signature will still compile.

Since they are private, they cannot be used outside the interface definition. They also cannot be used in static interface methods without a static method modifier private interface methods can be used to reduce code duplication ...

public interface Schedule { default void wakeUp() { checkTime(7); } default void haveBreakfast() { checkTime(9); } default void haveLunch() { checkTime(12); } default void workOut() { checkTime(18); } private void checkTime(int hour) { if (hour> 17) { System.out.println("You're late!"); } else { System.out.println("You have "+(17-hour)+" hours left " + "to make the appointment"); }}}

Records A record declaration specifies a new record class, a restricted kind of class that defines a simple aggregate of values. A record declaration implicitly creates instance fields, which are private and final. These are called record "components". A record class has a method with the same name as the record component and an empty formal parameter list. Such methods act as the getter methods (aka accessor methods) for those fields. For example: ...

public record Student(int id, String name) //record header { } //record body This is roughly equivalent to the following class: public final class Student extends Record { private final int id; //record component private final String name; //record component public Student(int id, String name){ //canonical constructor this.id = id; this.name = name; } public int id(){ return id; } //accessor public String name(){ return name; } //accessor //hashCode, equals, and toString methods are also provided by the compiler. } Observe that the accessor methods do not follow the JavaBeans convention (where a getter method is prefixed with get). Further observe that instance fields are final and the class does not have any setters.

public enum Season { WINTER("Low"), SPRING("Medium"), SUMMER("High"), FALL("Medium"); private final String expectedVisitors; private Season(String expectedVisitors) { this.expectedVisitors = expectedVisitors; } public void printExpectedVisitors() { System.out.println(expectedVisitors); } } How do we call an enum method? Season.SUMMER.printExpectedVisitors(); ...

the compiler requires that the list of values always be declared first. The list of enum values ends with a semicolon ( ;). While this is optional when our enum is composed solely of a list of values, it is required if there is anything in the enum besides the values. We mark the instance variable final on expectedVisitors so that our enum values are considered immutable. Although this is certainly not required, it is considered a good coding practice


Kaugnay na mga set ng pag-aaral

Florida Real Estate Associate Exam Questions

View Set

World Geography Chapter 10 Review

View Set

Pathogenic Cocci of Medical importance

View Set

RN QBank Safe and Effective Care Environment (Management of Care and Safety and Infection Control)

View Set

FBLA-Intro to Information Technology

View Set

MKTG - CH. 9 +10, 11 + 12 - QUIZZES

View Set