Java why invocation of private method works

56 Views Asked by At

I wonder why this

public static void main (String[] args) throws java.lang.Exception
{   
    class Print {
        public String name = "Timur";
        private void writeObject() {
            System.out.println(name);
        }
    }
    class Write {
        public void callPrint(Print p) {
            p.writeObject();
        }
    }
    Print p = new Print();
    Write w = new Write();
    w.callPrint(p);
}

works in Java. Method writeObject is a private one, but still successfully called from other class object.
Question comes from definition of the ObjectOutputStream. It says that if we want to overwrite serialisation process, we should declare private void writeObject(java.io.ObjectOutputStream stream) throws IOException method of the serialisable object. Which means ObjectOutputStream could invoke it, nevertheless it's private.

0

There are 0 best solutions below