I have the following code. Two questions follows:
class Parent { private void test() { System.out.print("test executed!"); } static void print(){ System.out.println("my class is parent"); } } class Child extends Parent { static void print(){ System.out.println("my class is Child"); } } public class Inheritence { public static void main(String[] args) { Child p1 = new Child(); Parent p = new Child(); System.out.println("The class name of p is "+p.getClass()); System.out.println("The class name of p1 is "+p1.getClass()); System.out.println("p instance of child "+ (p instanceof Child)); System.out.println("p1 instance of child "+ (p1 instanceof Child)); //p.test(); p.print(); } } The output is:
The class name of p is class Child The class name of p1 is class Child p instance of child true p1 instance of child true my class is parent I thought the classname for p will be Parent, since it is of type Parent. However, it prints as Child. so how would I get the type of p.
Second question here is whether private methods are inherited or not. while many articles including this, comments that private methods are not inherited, I see in the below example it is inherited. It could be some type casting issues below.
class Child1 extends Parent1 { } public class Parent1 { private void test() { System.out.print("test executed!"); } public static void main(String[] args) { Parent1 p = new Child1(); p.test(); Child1 c = new Child1(); //c.test(); The method test from parent1 is not visible } } Output is : test executed! here I am calling test method on Child1 object which is of type Parent1. Child1 has no test method since it is not inherited. but I still get the output, which indicates the private methods are inherited! If test was a protected method, and I override in child class, it is the overridden method that gets executed though the type of object on which it is called is parent(parent p1 = new child1());
EDIT: After few comments, I made class Parent1 and class Child1 seperate and a new Class called App that constructs a parent and child object. now I cannot call p.test in the code below.
class Child1 extends Parent1 { } class Parent1 { private void test() { System.out.print("test executed!"); } } public class App1{ public static void main(String[] args) { Parent1 p = new Child1(); p.test();//The method test from parent is not visible Child1 c = new Child1(); //c.test(); //The method test from parent1 is not visible } }