Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

how to access child class variable in parent class in java

In simple words:

- the left side before "=" means what the object may do, 
- the right side after "=" means how an object will do.

So:

public class Parent {
    private String someVar = "Parent variable";
    public void someMethod(){
        System.out.println(someVar);
    }
}

public class Child extends Parent{
    protected String someVar = "Child variable";
    public void someMethod() {
        System.out.println(someVar);
    }
}

public class Main {
    public static void main(String[] args) {
        Parent p = new Child();
        p.someMethod();
        Parent p2 = new Parent();
        p2.someMethod();
    }
}

out:
Child variable
Parent variable
 
PREVIOUS NEXT
Tagged: #access #child #class #variable #parent #class #java
ADD COMMENT
Topic
Name
5+1 =