Java:Method called from subclass in superclass constructor - java

class AA{
int x;
protected AA(){init (1008);}
protected void init(int x)
{
this.x = x;
}
}
class BB extends AA{
public BB() {
init(super.x * 2);
}
public void init(int x)
{
super.x = x+1;
}
}
public class Main {
public static void main(String[] args) {
BB tst = new BB();
System.out.println(tst.x);
}
}
I know that this code will print 2019. Yet I do not understand why the superclass constructor,when called, will use the init method from de subclass instead the one from the superclass.

Yet I do not understand why the superclass constructor,when called, will use the init method from de subclass instead the one from the superclass.
Because that's the one associated with the object being constructed. this within the superclass constructor is a reference to the subclass object being constructed, so just like any other call to init using that reference, it uses the subclass's init.
This may help, note the lines with comments on the end — the comments say what those lines output:
class AA{
int x;
protected AA() {
System.out.println(this.getClass().getName()); // "BB"
System.out.println(this instanceof BB); // true
init(1008);
}
protected void init(int x)
{
this.x = x;
}
}
class BB extends AA{
public BB() {
init(super.x * 2);
}
public void init(int x)
{
super.x = x+1;
}
}
public class Main {
public static void main(String[] args) {
BB tst = new BB();
System.out.println(tst.x);
}
}
It's because subclasses can override methods that calling non-final, non-private methods from a constructor is usually best avoided.

Related

In Java how to refer subclass variable without declaring that variable in parent class?

public class MyTest {
public static void main(final String[] args) {
B b = new B();
b.print();
}
}
class A {
private final int x = 5;
protected int getX() {
return x;
}
public void print() {
System.out.println(getX());
}
}
class B extends A {
private final int x = 10;
#Override
protected int getX() {
return x;
}
}
In this example, I need to print subclass value in the parent class.
It is working fine. No issue.
Now it is printing 10.
But I do not want to define that property in the parent class A.
Because in this example this x datatype is very simple. So no issue.
But in real-time I want to use other datatype which may be another Class variable or List<something> which have huge data.
So ultimately I do not wish to store that value in Class A.
Because it is redundant data. It will slow down in my Hibernate thing.
Please let me know, how to achieve this without declaring variable in parent class. But I still need to use subclass variable in parent class.
make abstract your class A and the getX(); method.
public class Test {
public static void main(final String[] args) {
B b = new B();
b.print();
}
}
abstract class A {
protected abstract int getX();
public void print() {
System.out.println(getX());
}
}
class B extends A {
private final int x = 10;
#Override
protected int getX() {
return x;
}
}
and override the toString method in place of your print method
#Override
public String toString() {
return String.valueOf(getX());
}
the final code
public class Test {
public static void main(final String[] args) {
B b = new B();
System.out.println(b);
}
}
abstract class A {
protected abstract int getX();
#Override
public String toString() {
return String.valueOf(getX());
}
}
class B extends A {
private static final int X = 10;
#Override
protected int getX() {
return X;
}
}
you could also define as static your x variable
But as say Andrew Tobilko you can consider also to use an interface if A doesn't represent a stateful entity.
It's certainly the best solution for your case, mix the use of an interface and an abstract class
public class Test {
public static void main(final String[] args) {
B b = new B();
System.out.println(b);
}
}
interface MyInterface {
int getX();
}
abstract class A implements MyInterface{
#Override
public String toString() {
return String.valueOf(getX());
}
}
class B extends A {
private static final int X = 10;
#Override
public int getX() {
return X;
}
}
You need the getX within the parent class, but you don't have information enough to implement this method there.
You can declare this class as abstract and mark the method with abstract as well. Doing that, you are handing the responsibility of method implementation over its subclasses and preventing from parent field declaration.
If the A doesn't describe any state (only actions/methods), you should consider replacing it with an interface. At the current state, it is the case.
You could make the parent class abstract, eliminate the property in the parent class, make getX() abstract, and then leave print() as concrete. Then just use the concrete implementation of getX() in the child class.

Invoking a method in anonymous (inner) classes

interface Example{
void methodExample();
}
class Y{
void do(Example x) { }
}
class X{
void methodX() {
Y y = new Y();
y.do(new Example() {
public void methodExample() {
System.out.println("methodExample");
}
});
}
}
I want to create a main class and call methodExample. How would I do that?
Since your class implements Example interface, and because void methodExample() is present on that interface, all you need to do is to reference the object by its interface, and call its method:
class Y{
public void doIt(Example x) {
x.methodExample();
}
}
The above works, because objects of all classes implementing Example, including all anonymous implementations, are known at compile time to implement methodExample().
If you don't have access to class Y then, the only way to do is to override doIt() itself first, using anonymous inner class and then, call the overridden method, e.g.:
class X {
void methodX() {
Y y = new Y() {
#Override
void doIt(Example x) {
x.methodExample();
}
};
y.doIt(new Example() {
public void methodExample() {
System.out.println("methodExample");
}
});
}
}
To call this, you can simply do:
public static void main(String[] args) throws Exception {
X x = new X();
x.methodX();
}

How can my subclass properly inherit a static variable

public abstract class SuperClass {
public int x, y;
public static int z;
}
I want every subclass of SuperClass to have the static variable z. Naturally z will contain a different value for each subclass. I'm hoping to avoid defining z in every subclass, since it's going to be a functional dependancy of values x and y; Is this possible?
Unlike instance variables that are "one per instance", static variables are not "one per subclass" - they are "one per declaring class". In other words, subclasses of SuperClass share SuperClass.z, but they cannot "override" it on a class-by-class basis.
It does not mean that you cannot implement it yourself: on way to make your own per-subclass storage of integers is adding a static Map<Class,int> zs to SuperClass, with optional functions for accessing the data:
public abstract class SuperClass {
public int x, y;
private static Map<Class,Integer> zs = new HashMap<Class,Integer>();
protected static int getZ(Class c) {
Integer res = zs.get(c);
return res == null ? -1 : res.intValue();
}
protected static void setZ(Class c, int v) {
zs.put(c, v);
}
}
class SubClassOne extends SuperClass {
public int getZ() {
return SuperClass.getZ(SubClassOne.class);
}
}
class SubClassTwo extends SuperClass {
public int getZ() {
return SuperClass.getZ(SubClassTwo.class);
}
}
Probably the best way to do this is to have a z() method or similar in the abstract class, and override the method in the subclasses you want.
Example:
public abstract class SuperClass {
public int x, y;
protected int z() {
return 42; // protected so only subclasses can see it - change if required
}
}
public class SubClassOne extends SuperClass {
public void foo() {
// do something...
int z = z();
// something else...
}
}
public class SubClassTwo extends SuperClass {
#Override
protected int z() {
return 1;
}
// use z() accordingly
}
if i understand you correctly then do
public abstract class SuperClass {
public int x, y, z;
public SuperClass(int z) {
this.z = z;
}
}
then any class that extends this class inherits z;

Java : Using parent class method to access child class variable

I have the following scenario :
public class A {
private int x = 5;
public void print()
{
System.out.println(x);
}
}
public class B extends A {
private int x = 10;
/*public void print()
{
System.out.println(x);
}*/
public static void main(String[] args) {
B b = new B();
b.print();
}
}
On executing the code, the output is : 5.
How to access the child class(B's) variable(x) via the parent class method?
Could this be done without overriding the print() method (i.e. uncommenting it in B)?
[This is important because on overriding we will have to rewrite the whole code for the print() method again]
EDITED
More Clarification :-
The motive of the question is to use the value of a child class private variable from its parent class method. This doesn't require changing the value of the parent class private variable in order to achieve the desired result.
The answers posted here, though, led me to my desired answer, which I have posted below.
(Thanks all for your time and help )
class A {
private int x = 5;
protected int getX() {
return x;
}
protected void setX(int x) {
this.x = x;
}
public void print() {
// getX() is used such that
// subclass overriding getX() can be reflected in print();
System.out.println(getX());
}
}
class B extends A {
public B() {
// setX(10); // perhaps set the X to 10 in constructor or in main
}
public static void main(String[] args) {
B b = new B();
b.setX(10);
b.print();
}
}
EDITED
Below is a general answer using abstract class and method to solve similar scenario:
abstract class SuperA {
protected abstract Object getObj();
public void print() {
System.out.println(getObj());
}
}
class A extends SuperA {
#Override
protected Object getObj() {
// Your implementation
return null; // return what you want
}
}
class B extends A {
#Override
protected Object getObj() {
// Your implementation
return null; // return what you want
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}
After reading all the answers posted here, I got what I was looking for. The following is what I feel is the best answer for my question :
public class A {
private int x = 5;
protected int getX(){
return x;
}
public void print(){
System.out.println(getX());
}
}
public class B extends A {
private int x = 10;
protected int getX(){
return x;
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}
Setting up a protected getter and overriding it is better than overriding the print() method itself, as there could be any other huge method in place of the print method which might need to access the value of the child class variable(s).
To solve your question you have to define the fields in the parent class A like protected (so it will be inherited on the child class) and set the field value x inside the constructor in the child class B. The print method is also inherited from A class so you can invoke it directly from parent class.
I hope this can help you.
public class A
{
// fields declaration
protected int x = 5;
public void print()
{
System.out.println(x);
}
}
public class B extends A
{
public B()
{
// set child x value. The field have been defined in the parent class
x = 10;
}
public static void main(String[] args)
{
A a = new A();
a.print(); // print 5
B b = new B();
b.print(); // print 10
}
}
You can always add it to the constructor:
public class B extends A {
//this line is unnecessary: private int x = 10;
/*public void print()
{
System.out.println(x);
}*/
public B()
{
x=10;
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}
The reason it won't work as you try it is that default values only get evaluated once. So when it's default 5 in A, it stays 5 even though you used default 10 in B.
You should expose a getter for the value you want and override that in the child class.
Like so:
public class A {
private int x = 5;
public void print()
{
System.out.println(getX());
}
protected void setX(int x)
{
this.x = x;
}
protected int getX()
{
return x;
}
}
public class B extends A {
/*public void print()
{
System.out.println(x);
}*/
public B()
{
setX(10);
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}

how to feed input from child class to parent class in java?

Ex
class A () {
class A(int a, int b) {
}
}
class B extends A {
int m;
int n;
class B()
{
getInput(); // i wanna invoke this method first before calling super(). But it does not allow in Java. How to work around this ?
super(m,n);
}
public void getInput() {
Scanner scanner = new Scanner(System.in);
m = scanner.nextInt();
n = scanner.nextInt();
}
public static void main () {
B b = new B();
}
}
You can force your super class to run a method at the beginning of its constructor and then override that method in the subclass. Many frameworks have a "setup" type method that you can override to accomplish such things.
public class A {
protected int a; // 'protected' so subclass can see it
protected int b;
public A() {
setup(); // Runs whatever setup method is implemented, even in subclasses
}
protected void setup() { /* nothing */ } // 'protected' to be overridden by subclass
}
public class B extends A {
public B()
{
super();
}
/**
* When A's constructor calls setup(), this method will run.
*/
#Override
protected void setup() {
Scanner scanner = new Scanner(System.in);
a = scanner.nextInt(); // Stores value in A's protected variable.
b = scanner.nextInt();
}
}
Depending on the specifics of the classes you're writing, this is where you might have multiple constructors, public or protected methods for setting values, etc. This is where Java is fairly flexible. As the comments below indicate, this isn't a very good practice in constructors, but I'd need more context to figure out how to accomplish what you're asking.
You could chain multiple constructors together as jbrookover alluded to in such a manner. Sligtly convoluted though:
class A () {
public A(int a, int b) {
}
}
class B extends A {
int m;
int n;
public B()
{
this(new Scanner(System.in));
}
private B(Scanner scanner) {
this(scanner.nextInt(),scanner.nextInt())
}
private B(int m, int n) {
super(m,n)
this.m = m;
this.n = n;
}
public static void main (String ... args) {
B b = new B();
}
}

Categories

Resources