(Java) Difference ways of instantiating subclasses - java

I have these two classes:
public class A {}
public class B extends A {}
In the main class, I would declare:
A a = new B();
B b = new B();
What is the difference between a and b ? Is this what we called a subtyping in java?

The difference between a and b is that with a you can only use the public API that the A class provides even though its really a B type object, but with b, you can use both the A's public API as well as B's public API.
For example:
Suppose A and B are defined as follows:
// A.java
public class A
{
public void x()
{
z("X");
}
public void y()
{
z("Y");
}
protected void z(String message)
{
System.out.println(message);
}
}
// B.java
public class B extends A
{
public void a()
{
z("A");
}
public void b()
{
z("B");
}
}
And here's a demo:
// Demo.java
public class Demo
{
public static void main(String[] args)
{
A a = new B();
B b = new B();
// Can only call A's public methods
a.x();
a.y();
// a.a(); Can't use
// a.b(); Can't use
// Can call all public methods
b.a();
b.b();
b.x();
b.y();
}
}

Yes, there is difference between them. Accssibility of methods are different depends on what kind of reference you use.

A a = new B();
B b = new B();
a is a reference of Class A and b is a reference of class B. super class always can be used to point subclass object.
reference a able to access only super class method and properties
reference b able to access super class and it's own method and properties
one important thing is, ability of accessibility of function and properties will decided at runtime.

In below two cases
A a = new B();
a is an instantiation of B and of type A.
whereas in
B a = new B();
a is an instantiation of B and of type B.
The important thing to note here is that (in the first case) if you call a.someMethod(), the method of B will be called, not the method of A (this is called dynamic binding, as opposed to static binding).

This is basic inheritance. In the B b = ... case you can access all methods and variables provided from A and B but in the A case you can only use the methods and variables in the A case.
B gets typecasted into A when it is created, but that information is not required by the compiler.
public class A {
int x;
}
public class B extends A {
int y;
}
A a = new B();
B b = new B();
int c = a.x; //works
int c = a.y; //doesn't work
int c = b.y; //works
int c = b.x; //works
Remember, that you can always cast an object "downwards" in the inheritance chain. But you should not cast a object upwards because the variables for the subclass might be used even though they dont exist, for exmaple B b = new A(); So b.y is dangerous since the B object doesn't have an y variable defined.

Related

Java accesing properties with same name in both classes

I have 2 classes, A and B which B inherits from A.
Both classes have a property of type int called w.
In class A w is public and in class B w is private.
I made an object of type A using B constructor - A a = new B()
Yet when i tried to access B's properties i found out i can only access variables or methods from class A even though i made an object of type B.
I thought that this was only relevant if both classes didnt have the same methods or variables.
But in this case both classes have a variable named w yet i can only access the value stored in the A class. Why is this so?
class A
public class A {
public int w;
private static String str = "K";
public A() {
str+="B";
w+=str.length();
str+=w;
}
#Override
public String toString() {
return str.charAt(w-2)+"P";
}
}
class B
public class B extends A {
public static int w = 2;
private String str = "W";
public B(int x) {
w+=super.w;
str+=super.toString()+w;
}
#Override
public String toString() {
return super.toString() + str;
}
}
Testing class
public class Q1 {
public static void main(String[] args) {
A a = new A();
A a2 = new B(1);
System.out.println(a);
System.out.println(a.w);
System.out.println(a2);
System.out.println(a2.w);
B b = new B(2);
System.out.println(b);
}
}
Since the type of variable a is [class] A, the variable can only access members and methods of class A (depending on the access specifiers) – even though the actual type of variable a is class B.
Refer to method paintComponent, in class javax.swing.JComponent. The type of the method parameter is Graphics but the actual type of the parameter is Graphics2D (which extends Graphics). However, in order to access the methods of Graphics2D, you must first cast the parameter, i.e.
Graphics2D g2d = (Graphics2D) g;
This is a fundamental aspect of the object-oriented paradigm.
Refer also to the comment to your question by #ArunSudhakaran
Similarly, if you want variable a to access the w member of class B, you need to cast a.
A a = new B();
if (a instanceof B) {
B b = (B) a;
System.out.println(b.w);
}
If you are using at least Java 14, you can use Pattern Matching for the instanceof Operator
A a = new B();
if (a instanceof B b) {
System.out.println(b.w);
}
Also refer to the book Effective Java by Josh Bloch.

Is this correct to pass this keyword as parameter for member objects creation in java?

Here is my definition of class
class A {
B b = new B(this);
}
Is it correct to pass this keyword as parameter for member
objects creation in the class' definition?
if yes where can we use this?
It is correct in the sense that it compiles and runs.
It may be dangerous because your object is not fully initialized, so using it inside the member object's constructor may not be safe.
At a higher level, it's a bad practice to create new objects in constructor, see Injection of Dependencies pattern.
Update: this code certainly compiles:
class B {
B(A a) {
}
}
class A{
B b = new B(this);
}
If you had some kind of context object which is always created, you could use this pattern to avoid using an inner class.
So instead of this:
class A {
B b = new B();
class B {
void printA() { System.out.println(A.this); }
}
}
You could have two separate files:
class A {
B b = new B(this);
}
class B {
A a;
B(A a) { this.a = a; }
void printA() { System.out.println(a); }
}

is there a vitual parameter invocation as there is for virtual method invocation in java? [duplicate]

class A
{
int a = 2, b = 3;
public void display()
{
int c = a + b;
System.out.println(c);
}
}
class B extends A
{
int a = 5, b = 6;
}
class Tester
{
public static void main(String arr[])
{
A x = new A();
B y = new B();
x.display();
y.display();
}
}
Why does the output come out as 5,5? And not 5,11?.How would the y.display() method work?
why does the output comes 5,5?
Because A.display() only knows about the fields A.a and A.b. Those are the only fields that any code in A knows about. It looks like you expect the declarations in B to "override" the existing field declarations. They don't. They declare new fields which hide the existing fields. Variables don't behave virtually in the way that methods do - the concept of overriding a variable simply doesn't exist. From the JLS section 8.3:
If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
You can get the effect you want by changing B so that its constructor changes the values of the existing fields that it inherits from A instead:
class B extends A {
B() {
a = 5;
b = 6;
}
}
Note that these are not variable declarations. They're just assignments. Of course in most code (well, most code I've seen anyway) the fields in A would be private, so couldn't be accessed from B, but this is just example for the purpose of explaining the language behaviour.
In class A you declare fields a and b. The method display uses these fields. In class B you declare NEW fields of the same name. You're actually hiding the old fields not "overriding" them. To assign different values to the same fields use a constructor:
class A {
A(int a, int b) {
this.a = a;
this.b = b;
}
A() {
this(2, 3);
}
int a,b;
public void display() {
int c=a+b;
System.out.println(c);
}
}
class B extends A {
B() {
super(5, 6);
}
}
When doing this:
class B extends A
{
int a = 5, b = 6;
}
you are not redefining a and b, you're creating new variables with the same names. So you end up with four variables( A.a, A.b, B.a, B.b).
When you call display() and calculate the value of c, A.a and A.b will be used, not B.a and B.b
There isn's anything called variable overriding. That is why you are getting the same result in both the cases.
The reason is that Java uses the concept of lexical scope for variable resolution.
Fundamentally, there are two possible options to resolve free variables in a function ('free' means not local and not bound to function parameters):
1) against the environment in which the function is declared
2) against the environment in which the function is executed (called)
Java goes the first way, so free variables in methods are resolved [statically, during compilation] against their lexical scope (environment), which includes:
method parameters and local method variables
field declarations in the class containing method declaration
public field declarations in parent class
and so on, up the chain of inheritance
You would see this behaviour implemented in most programming languages, because it is transparent to developer and helps prevent errors with shadowing of variables.
This is opposite to the way methods work in Java:
class A {
public void foo() {
boo();
}
public void boo() {
System.out.println("A");
}
}
class B extends A {
#Override
public void boo() {
System.out.println("B");
}
}
class Main {
public static void main(String[] args) {
B b = new B();
b.foo(); // outputs "B"
}
}
This is called dynamic dispatch: method call is resolved dynamically in runtime against the actual object, on which it is called.
When you compile your code it pretty much becomes like:
class A extends java.lang.Object
{
int a=2,b=3;
public void display()
{
int c=a+b;
System.out.println(c);
}
}
class B extends A
{
int a = 5, b = 6;
public void display()
{
super(); //When you call y.display() then this statement executes.
}
}
class Tester
{
public static void main(String arr[])
{
A x = new A();
B y = new B();
x.display();
y.display();
}
}
And hence, when super calls, the method of class A is being called.
Now go to method of class A. Here int c = a + b; means
c = this.a + this.b; which is 2 + 3.
And the result is 5.
Class B declares variables in B scope, public void display() is part of A class and knows only about its own scope variables.
It's the inheritance functaionality which gives the output 5,5.
Java doesn't have anything like variable overriding. Thus, when the method display() is invoked, it accesses the variables inside the parent class 'A' and not the variables inside the subclass 'B'.
It can be explained with the same reason of why you can't print a variable declared in a subclass (and not in superclass) inside superclass method. The superclass method simply doesn't have access to the subclass variables.
However, you'll be able to print 5,11 if you have accessor methods to the fields in both the classes and you use those accessor methods to get the values instead of directly accessing using variable names. (even if the display() method is present only in superclass). This is because the overridden accessor methods are invoked (in second case) which return the values from the subclass.
Why does the output come out as 5,5? And not 5,11?
Whenever we have same instance variables (applicable to class variable as well) in a class hierarchy, the nearest declaration of the variable get the precedence. And in this case, nearest declaration of a and b from display () method is A’s. So class B’s instance variables go hidden. Hence in both cases, 5 gets printed.
How would the y.display() method work?
Another alternative is to have getter in both classes to get value of a and b.
class A
{
int a = 2, b = 3;
public int getA() {
return a;
}
public int getB() {
return b;
}
public void display()
{
int c = getA() + getB();
System.out.println(c);
}
}
class B extends A
{
int a = 5, b = 6;
public int getA() {
return a;
}
public int getB() {
return b;
}
}
class Tester
{
public static void main(String arr[])
{
A x = new A();
B y = new B();
x.display();
y.display();
}
}
Prints
5
11

Instance of child in parent class

I have class In java: A. And class B which extends class A.
Class A hold instance of class B.
I notice that when I call the constructor of class B (when I init this parameter in class A), It does super(), create a new instance of A and init all it fields.
How I can tell class B that the concrete instance of class A (which init it field) - it his parent class?
Your question is really hard to understand, but I guess the problem is this this (your approach):
public class A {
public B b = new B();
}
public class B extends A {
}
So, when you run new A() you get a StackOverflowError.
In my practical experience, I never needed a design like that, and I'd strongly recommend to re-think your approach. However, if it is really needed, you could use a dedicated init() method, e.g.:
public class A {
public B b;
public void init() {
b = new B();
}
}
A a = new A();
a.init();
If you needed A within B you could just do it with a custom constructor for B:
class B extends A {
A a;
public B() {
super();
this.a = this;
}
}
This case is harder though so you need:
class A {
B b;
}
class B extends A {
public B() {
super();
b = this;
}
}
Note that you should not pass the B into the call to super() as B will not be initialized, you should do it as the last step in the constructor of B.

About Java Assignment Operator

If i define
class A {
public int a;
public float b;
public A() {
a = 10;
}
}
class B extends A {
public B() {
a = 2;
}
}
class C extends A {
public C() {
b = 2.0f;
}
}
And in main
public static void main(//...) {
A a = new A();
B b = new B();
C c = new C();
a = b; //error?
b = c; //this one too?
}
I am not sure about the first error, it looks fine. You should in future post the exact error message along it. You should never ignore error messages since they tell something about the cause of the problem. The second error is obvious, it's a type mismatch: C does not extends B, so you cannot assign an instance of C to a reference which is declared as B. To fix it, you should declare it as C, A or Object (since it is the implicit superclass of all classes).
Further, your class C doesn't compile since the constructor is named A() instead of C(), but that'll probably be a copypaste error ;)
See also:
Inheritance tutorial

Categories

Resources