Put inside the extended class the parent class - java

I have a problem with an extended class.
This are the classes:
class A{
}
class B extends A{
}
Now the problem is that I have a method that returns A , something like this:
public A doSomthing(){
}
And now I try to do something like this:
public static void main(){
B b = new B();
b = doSomething();
}
But it doesn't seem to work. Is there any way to solve this problem?
The only thing I thought about is it to have something like this:
class B extends A{
public B(A a){
copy all the fields from A to B}
}
And then do:
A a = new A();
a = doSomthing();
B b = new B(a);
Is there a better option?

Fundamentally I think you've missed what the assignment operator does. This statement:
b = doSomething();
changes the value of b to whatever the doSomething() method returns. It doesn't depend on the existing value of b at all. So similarly, when you have:
A a = new A();
a = doSomthing();
... it would make more sense to write:
A a = doSomething();
Now if you need to create an instance of B based on an instance of A, then it may well make sense to write:
A a = doSomething();
B b = new B(a);
or just:
B b = new B(doSomething());
... but you need to understand when existing values are used and when they're not.
Usually I find that when I need to do something like that, it's actually better to use composition than inheritance anyway - that B should have a reference to an existing A rather than extending A. That's certainly something to consider, but without a concrete example we can't say for sure.

You instantiate your object b to be of Type B instead of A therefore polymorphism would not work when calling doSomthing
Change your object b to be of Type A

Java does not have multiple inheritance (c# example) to enforce method signatures. Instead it would make sense to
public static A doSomthing(){
A result = new A();
...
return result;
}
Then you can use:
A a = A.DoSomthing();
B b = (B)A.DoSomthing();

Related

I have some issue about casting in java

public class A {
private String superStr;
public String getSuperStr() {
return superStr;
}
public void setSuperStr(String superStr) {
this.superStr = superStr;
}
}
public class B extends A {
private String subStr;
public String getSubStr() {
return subStr;
}
public void setSubStr(String subStr) {
this.subStr = subStr;
}
}
And I expect result likes below
public static void main(String[] args) {
A a = fuc();
B b = new B();
b = (B) a;
b.setSubStr("subStr");
System.out.println(a.getSuperStr() + b.getSubStr());
}
private static A fuc() {
A a = new A();
a.setSuperStr("super");
return a;
}
but java.lang.ClassCastException is ocuured.
How can I cast this?
I want use subclass variable and super class variable.
thank you
How can I cast this?
You can't. You can only cast when the object in question has an "is a" relationship with the type. In your case, you have an A object (the one from fn), which is not a B. (All B objects are As, because B extends A, but not all A objects are Bs.)
Consider: Let's call B Bird and A Animal: A Bird is an Animal, but not all Animals are Birds. So we can treat all Birds as Animals, but we cannot treat all Animals as Birds. When you're using a variable of a given type to refer to an object, you're treating the object as being of that type (e.g., B b = (B)a tries to treat the Animal a as a Bird).
Side note: There's no point to the indicated part of the code:
B b = new B();
// ^^^^^^^^^^
b = (B) a;
Since the very next line assigns to b (well, it would if it would compile), there's no purpose served by doing new B() and assigning that to b just beforehand. (Unless the B constructor has side-effects, which is generally a Bad Idea™.)
Casting a particular object to another types does not magically convert it into an instance of that class (or at least not in Java); Therefore, the object referenced by variable a does not e.g. have the field subStr to use despite that the object referenced by b after executing B b = new B(); does.
The others have already explained why you can't do that. I'm here to give you a simple alternative. Your B class could have a constructor that had an A as argument and you would simply wrap that A so you could "transform" it to a B. Using that your code would look way more clean, it would actually work and you were following a good design pattern. For more information check the Decorator Pattern

How to set a field with out creating an object in java

I can't modify either Class A or Class B. And both Class A & B are huge in size (with several nested Classes and hundreds of parameters). And with multiple threads, memory foot print is impacting the performance.I'm checking all ways to reduce memory usage. Basically I'm trying to limit the scope of Class B instance so that GC can work on it at the earliest.
(For Your Information: I already knew that I can do by B b = new B(); b.setS("Calm Down"); a.setB(b);)
Here is the scenario:
Class A{
private B b;
public getB{return b}
public void setB (B b){this.b = b;}
}
Class B{
private String s;
//getters and setters for s}
Class MyNeed{
A a = new A();
// Here I'm trying to create an obj B and set S and then pass that obj to a.setB().
a.setB (new B().setS("Param S Set"));
}
So I guess that new B() is local to setB(). so in the very next line new B() is out of scope.
But this way in eclipse, I'm getting error that setB() can't accept void. I guess it is setS() returning void.
May be I'm missing some concepts. But I want to have something such simple. How to implement this.
You can try to have a constructor within the class A:
class A{
private B b;
public B getB(){
return b;
}
public void setB (B b){
this.b = b;}
}
public A(S s){
this.S = s;
}
}
So when you do a.setB(), you can just do a.setB(s) and that will set the object S for that A object.
a.setB (new B().setS("Param S Set"));
Ok, That statement starts by creating a new B instance, then it calls the setS method on that instance, passing it the string "Param S Set". Finally, it calls a.setB(...) passing the value returned by the setS() call.
As you already know, that doesn't work because setS() returns void.
May be I'm missing some concepts. But I want to have something such simple. How to implement this.
{
B b = new B();
b.setS("Param S Set");
a.setB(b);
}
What you are trying is wrong. setS() does not return B instance.
You will not save any resources by writing one-liners.
GC will also not clean anything if you set B to A as long as A has a reference to B.
I got it using builder design pattern. Thanks to #Builder by lombok.
Thank you all.

Class/object Casting [duplicate]

This question already has answers here:
Downcasting in Java
(12 answers)
Closed 8 years ago.
I am getting an exception for the following code.
class A {
void foo() {
System.out.println("Running foo()");
}
}
class B extends A {
void foo() {
System.out.println("Overidden foo()");
}
}
public class Casting {
public static void main(String[] args) {
A obj = new B();
obj.foo();
// B ref = (B) obj;
// ref.foo();
B ref = (B) new A();
ref.foo();
}
}
But if I run
B ref = (B) obj;
ref.foo();
instead of
B ref = (B) new A();
ref.foo();
it works properly.
Can anyone explain what is happening here.?
obj is an instance of B because you created it using the contructor of class B. This is why B ref = (B) obj; works fine.
In B ref = (B) new A(); you are simply casting an object of type A created using the constructor of A (which is the parent class) to a subclass type which will cause a java.lang.ClassCastException. The opposite casting would work, i.e.
A ref = (A) new B();
ref.disp();
in which case you converting an instance of a subclass to its parent which is fine since an object of type B is also an instance of A.
It's pretty easy to explain.
By doing new A() you receive an A-object. Then you tell the JVM it's of type B, but that's obviously wrong and the JVM can't cast from A-type to B-type, how should Java know how to do that? It's not sure that A has the same methods as B. It's just a parent, B could have methods A hasn't. If you could cast from A to B you could have B objects that don't behave like B objects and don't have the B classes methods.
If you have a B-object you can treat it like a A-object because every B-object has at least the same methods, constructors and ivars.
An example using ducks:
Imagine you have got an abstract Duck class (but you didn't declared it as abstract). This class is the parent class of all other duck classes and also including RubberDuck. As reason of that the Duck class just has some basic methods like getSize but no method like walk or eat (a rubber duck can't eat herself).
What would happen if you create a duck object and downcast it to BuffleheadDuck and you would try to invoke the walk method? A BuffleheadDuck duck knows how to walk, but an abstract duck can't walk.

The difference between "C c = new C()" and "A c = new C()" when C is a subclass of A in Java

Let's say we have class A as a parent class, and class C that extends it.
class A
{
void m()
{
System.out.println("A.m");
}
}
class C extends A
{
#Override
void m()
{
System.out.println("C.m");
}
}
What's the difference between reference A a and C c when we use them to point to the same object type, for example A a = new C(); and C c = new C();?
From this question: Java inheritance vs. C# inheritance, it looks like that as a and c points to object type of C, and there seems no difference in using them.
I tested this code, and they all prints C.m.
class inherit {
void x(A a)
{
a.m();
}
public static void main(String[] args) {
System.out.println("hello");
A a = new C();
C c = new C();
a.m();
c.m();
new inherit().x(a);
new inherit().x(c);
}
}
That depends what the object is going to be used for.
If what you actually need is an object that has A's interface(i.e. A's type), it's strongly recommended to use A a = new C();. This way it makes it clear that you want an A interface, not a C implementation. Later when you change your mind, you can safely change it to A a = new Another_Subtype_Of_A(); without breaking other code.
This is especially true when A is an interface(In your case, A is a class). For example, if you just want a list, List list = new ArrayList(); is clearly better than ArrayList list = new ArrayList();. That's called "programming to interface, not implementation".
If you're creating an object that specifically needs C's interfaces(esp. those not present in A), you'd better choose C c = new C();. If you write A a = new C() instead, sooner or later you still have to cast the object to C(because A doesn't have all of your desired interfaces), so why bother?
It's not about the runtime type of the variable. You may only know you have a Vehicle object at compile time and based on user input, that may be a GarbageTruck or SportsCar.
GarbageTruck t;
...
t = new SportsCar(); //can't do this!
// so we do this:
Vehicle t;
if(user.isFast()) {
t = new SportsCar();
} else {
t = new GarbageTruck();
}
Java is all about Interfaces and Implementations.
An Interface is simply a set of public fields (methods & properties) the describe how users can interact with a class that implements the interface.
An Implementation is the code that actually makes those methods and properties do something. An Implementation can be a class that implements an interface, or it could be a subclass of some other implementation.
When you instantiate a class, you're writing code like:
Interface a = new Implementation();
Often times, we wrap the Interface and the Implementation all together... put another way, when we define a class, whether we're explicitly implementing an interface or not, we're defining an Interface with every public method we write.
Thus, it's the Interface that affects what methods we can call, but it's the Implementation that affects what happens when we call them.
firstly A is parent class and C is child class when you do A a = new A() then object of A is created and hold by A handle. When you do C c = new C() then object ofC is creating and C handle holds it.. But when you do A a = new C() then object ofC is created and Ahandle holds it. It means all the properties ofC is now been used. Although handle ofA is used by properties (instance) of C are used. This us polymorphism. Now it will used all the overloaded methods of C and not of A
Usages as an example
The difference come when you create a large project having methods created for child classes
Assume you have hello method
public void hello(C c) { }
In future you have another class B which extends A.. in that case you cannot use hello as its argument is of type C.. And imagine you have many classes as a child of A which need to use such method (then how many such methods you will create). Polymorphism is the rescue
You create hello with A as argument
public void hello (A x) { }
and now you can use same method for all the children of A..
A c = new C()
A b = new B()
Now all can use hello
this is the beauty of polymorphism

why i am getting ClassCastException in this case

Please tell me why i am getting ClassCastException in this case
I have type casted , the source of B class to A as shown below , but why i am still getting ClassCastException here .
public class A extends B
{
}
public class B {
public String getData() {
return "B";
}
}
public class Main {
public static void main(String args[]) {
A a = new A();
B b = new B();
a = (A) b;
System.out.println(a.getData());
}
}
It becomes more obvious if we play with different classnames:
public class Car extends SomethingWithWheels {} // was A extends B
public class SomethingWithWheels {} // was B
public class Train extends SomethingWithWheels {} // aahh, some C extends B
Now, lets cast again:
SomethingWithWheels somethingWithWheels = getItFromSomewhere();
Car car = (Car) somethingWithWheels;
The compiler has to complain, because somethingWithWheels (B) could be a Train instance (C), which can't be cast to Car (A).
You can't cast a base class to derived class. You can do the other way round though.
Because your instance "b" is not of type A (B does not extend A), so when you cast "b" to A it fails.
The opposite would work (casting an instance of type A to type B)
Because an instance of B is not an instance of A. It's really that simple.
If you create an instance of A, it's also a B - because that's what the subclassing means. However, if you create an instance of B, that is not an A, and can't be assigned/cast as such.
The only time you can cast is if the run-time class of an object is compatible with the type you're trying to cast to. You can't change the class of an existing object - which is what I think you might be trying to do here - only tell the compiler "look, I know it's really something more specific".
So as a counter-example, the following would work:
public static void main(String args[]) {
B b = new A();
A a = (A) b;
System.out.println(a.getData());
}
In this case, the variable b is declared to hold a reference to a B. It turns out that you populate it with an instance of A, but for the rest of the program the compiler isn't allowed to assume that b is an A, because it's not guaranteed. Since you know it's an A in your specific case, you insert the cast, which causes a run-time check that the object actually is an A. This succeeds, and from that point on you can call methods specific to A on your a variable.
In this case however there is no reason at all to do any casting - there are no extra methods available on the subclass that you'd need to call, and no methods which only take an A but not a B. Even if A overrode getData to do something different, you would still get this behaviour if invoking through a B reference.
You are downcasting and you try to cast a supertype to a subtype, thats why it does well during compilation but fails at runtime with ClassCastException.
You can call:
System.out.println(a.getData());
after removing the line where you try to cast the types

Categories