Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Class A() {
- Integer a1;
- Integer a2;
- }
- Class B() extends A {
- Integer b1;
- }
- Class A {
- protected Integer a1;
- protected Integer a2;
- }
- Class B extends A {
- Integer b1;
- }
- B b = new B();
- b.a1 = 3;
- b.a2 = 4;
- A aReference = new A()
- aReference.a1 = 1;
- aReference.a2 = 2;
- b1 is not present in the object so can not be set.
- A aReference = new B(); //reference of parent class and object of child class.
- aReference.a1 = 10;
- aReference.a2 = 20;
- ((B)aReference).b1 = 30;
- B bReference = new B();
- bReference.a1 = 10;
- bReference.a2 = 20;
- bReference.b1 = 30;
- Suppose you want to modify it from inside a method of B
- class B extends A{
- ....
- public void someMethod(){
- super.a1 = 10;
- super.a2 = 20;
- b1 = 40;
- }
- }
- If you want to modify the values of the state of child from parent class
- public class A{
- public void someMethod(){
- ((B)this).b1 = 10;
- a1 = 20;
- a2 = 30;
- }
- }
- class A {
- Integer a1=5;
- Integer a2=6;
- }
- class B extends A {
- }
- public class Inherit {
- public static void main(String[] args) {
- A obj = new B(); //casting
- A obj2=new A();
- obj.a1 = 10;
- obj.a2 = 12;
- System.out.println("value of a1 in class A :"+obj2.a1+" & value of a2 in class A :"+obj2.a2);
- System.out.println("value of a1 in class B :"+obj.a1+" & value of a2 in class B :"+obj.a2);
- }
- }
- B b = new B();
- b.b1 = 1;
- super.a1 = 3; // must execute from B class
Add Comment
Please, Sign In to add comment