Since Test2 inherits from Test1 you can simply use Test1 as the datatype.
public class Main {
public static void main(String[] args) {
Test1 obj1 = new Test1();
Test2 obj2 = new Test2();
populateAB(obj1);
populateAB(obj2);
System.out.println(obj1);
System.out.println(obj2);
}
public static void populateAB(Test1 obj) {
obj.setA(5);
obj.setB(10);
}
}
class Test1 {
private int a;
private int b;
public void setA(int a) {this.a=a;}
public void setB(int b) {this.b=b;}
@Override
public String toString() {
return String.format( "[a = %d; b = %d ]", a, b );
}
}
class Test2 extends Test1 {
private int c;
public void setC(int c) {this.c=c;}
}
Output:
[a = 5; b = 10 ]
[a = 5; b = 10 ]
Its the same with the toString() Method which is part of the Object class but every Object inherits from the Object class so they have access to those methods and also can be stored all together in an Object[] or something
Another example:
public class Main {
public static void main( String[] args ) {
Dog dog = new Dog( "Bello" );
Cat cat = new Cat( "Garfield" );
Animal[] animals = new Animal[] { dog, cat };
for ( Animal animal : animals ) {
System.out.println( animal.name );
}
}
}
class Animal {
public String name;
Animal( String name ) {
this.name = name;
}
}
class Cat extends Animal {
Cat( String name ) {
super( name );
}
}
class Dog extends Animal {
Dog( String name ) {
super( name );
}
}
Output:
Bello
Garfield
As you can see Im storing two different objects together as Animals since they both inherit from the Animal class.
Inheritancerather thanGenericsof Java. Commonly speaking, any sub-type instance can be assigned to their parent type variable.