Class Level Modifier Part 2

Java Modifiers Notes

strictfp (Strict Floating Point)

  • Introduced in Java 1.2
  • We can declare strictfp for classes and methods but not for variables.
  • Floating-point results vary across platforms; strictfp ensures IEEE-754 standard behavior.

strictfp Method

If a method is declared as strictfp, all floating-point calculations inside it follow IEEE-754 and become platform-independent.

abstract talks about no implementation, strictfp requires an implementation → so abstract strictfp is illegal for methods.

public abstract strictfp void m();   // ❌ Invalid
// Error: illegal combination of abstract and strictfp
    

strictfp Class

If a class is declared strictfp, all concrete methods in that class follow IEEE-754.
✔️ abstract strictfp is valid for classes.

abstract strictfp class Test {
}
    

Member Modifiers (Method / Variable Level)

Public Members

Public members can be accessed from anywhere, but the class must be public.

package pack1;

class A {
    public void m() {
        System.out.println("Hello");
    }
}
-------------
package pack2;

import pack1.A;

class B {
    public static void main(String... args) {
        A a = new A();  // ❌ Error: A is not public
        a.m();
    }
}
    

Error: pack1.A is not public. Cannot be accessed from outside the package.

Default Members

Default = package-private. Accessible only within the same package.

Private Members

Private members are accessible only within the same class.
❌ private abstract is illegal (child can't override private members).

Protected Members

Protected members are accessible:

  • Anywhere inside the same package
  • In child classes of another package (but only using child reference)
protected = (default access) + child class access
    

Protected Examples

package pack1;

public class A {
    protected void m1() {
        System.out.println("Hello");
    }
}

class B extends A {
    public static void main(String... args) {

        A a = new A();
        a.m1();   // ✔ valid (same package)

        B b = new B();
        b.m1();   // ✔ valid (child class)

        A aa = new B();
        aa.m1();  // ✔ valid (same package)
    }
}
    

Protected Access From Another Package

package pack2;

import pack1.A;

class C extends A {}

class D extends C {
    public static void main(String... args) {

        A a = new A();
        a.m1();   // ❌ invalid

        A ac = new C();
        ac.m1();  // ❌ invalid

        A a1 = new D();
        a1.m1();  // ❌ invalid

        C c = new C();
        c.m1();   // ❌ invalid

        D d = new D();
        d.m1();   // ✔ valid (child reference)
    }
}
    

Rule: A protected member in another package is accessible only in child classes and only through a child class reference.

0 Comments