Java add methods to super class [duplicate] - java

This question already has answers here:
Can a Java class add a method to itself at runtime?
(11 answers)
Closed 5 years ago.
I have a class that I don't have access to its source.
public class IDontHaveAccessToSource {...}
I'd like to add some methods to it, like so:
public class MyClass extends IDontHaveAccessToSource {
myMethod1() {...}
myMethod2() {...}
#Override
methodInIDontHaveAccessToSource(){...}
}
but it will give me a ClassCastException whenever I want to cast anything that returns IDontHaveAccessToSource to MyClass.
How can I do such things?
I don't want to use
public class MyClass {
IDontHaveAccessToSource obj;
MyClass(IDontHaveAccessToSource obj) {
this.obj = obj;
}
...
}
And there isn't any constructor available for IDontHaveAccessToSource. It 'gets created' by calling a function from another class:
IDontHaveAccessToSource obj = loadObject(filename);

You simply can't. An object that is created with new Super() can not be turned into a subclass object. If that would be possible, you would be able to break all rules of good object oriented programming.
You can only wrap around such objects. Think of decorator or facade patterns for example.

You cannot cast the object of more general class to more specific one since there is no object data in memory that relates to that specific part of your child class.
Say, you have class A that has a field fA. When you instansiate the object of that class, the field is initialized and takes some place in memory. Now you extend the class A to B by adding field fB. You create an object that allocates fA and fB in memory.
A aObj = new B(); is the proper cast since A knows about aF and once you access fA it will find the field in memory;
B bObj = new A(); This iswring since refering to bF won't be succeeded (instanciating of A did not allocate fB in memory)

Related

Why is the output of this program i=10? [duplicate]

This question already has answers here:
Overriding member variables in Java ( Variable Hiding)
(13 answers)
Closed 6 years ago.
class A
{
protected int i=10;
}
class B extends A
{
protected int i=15;
}
public class Test extends B
{
public static void main(String a[])
{
A obj=new Test();
System.out.print("i="+obj.i);
}
}
It's output is i=10, but how?
How is the memory allocation for the object will take place.
A obj=new Test();
Means, you are accessing the members of Class A and executing the methods of Test(polymorphism).
I suggest you to read the official docs on inheritance and polymorphism to understand deep.
Polymorphism is linked to objects not references. Since you are using a reference of type A, you will get A.i if you have method getI() in A and override it in B, then call obj.getI(), then you will get B.i's value
In java, Variable Overriding is not there. We have the concept of method Overriding.
In your code
A obj=new Test();
You can able to access members of A. If you have overridden same method in both the classes (Parent and Child). And you are calling that method with obj. This time you will get output from Child class overridden method. this is the concept of Polymorphism.
Line 1: A a = new A();
the method existence will be checked in A class and the method will be called from A class also.
a.g();//A class method will be called
System.out.print("i="+a.i);//A class i will be accessed
Line 2: A b = new B();
the method existence will be checked in A class and the method will be called from B class.
b.g();//B class method will be called and it will also check that it is` available in A also or not if not then compile time error.
System.out.print("i="+b.i);//A class i will be accessed

pass pojo and dao class as args by java generics and retrieve objects , need a dynamic generic class to accept these pojo and do as parameters [duplicate]

This question already has answers here:
Instantiating a generic class in Java [duplicate]
(10 answers)
Closed 8 years ago.
I having one requirement where I may pass any pojo and do as an argument like this
public class Genericclass <pojo,dao> {
//What I am expecting is when I call a method of this
class it should give me pojo object
public pojo getPojo(){
//create new object of the pojo
return pojo type OBJ;
}
Public dao getdao(){
//create new day OBJ
return dao OBJ;
}
}
i may use this while calling any type of pojo ex
Public class Temp {
Psvm(string args[]){
Add(Generic class<emppojo.class,empdao.class>);
//emp or dept or what ever I may pass
// I will do some business logic and create OBJ for
generic claa and I will use getpojo and getdao methods
for creating new objects and I will get dao object call a
method,
Sorry if I did any coding mistake . give me a solution
based on my requirement
}
// thanks in advance
Due to java type erasure, at runtime the generic class is not known. This means you have not access to the class of the generic type at runtime. The link of sp00m shows the work around: Pass in the class to your constructor or getPojo() method.
public pojo getPojo(Class pojoClass){
return pojoClass.newInstance();
}

cannot understand interface in java

I am looking at the Interface chapter provided on the Java website
Using Interface as a type
So my understanding was that the whole point of interface is that it is like a class but it's not possible to form objects from it, but this page says how to use interface as a data type. the line Relatable obj1 = (Relatable)object1; seems to create an object of type Relatable which is an interface. Although I must say that the new keyword has not been used here, thus not really creating a reference to an object of type Relatable. Is that really the cause for this line NOT creating an object of type Relatable?
Again, it further says
If you make a point of implementing Relatable in a wide variety of
classes, the objects instantiated from any of those classes can be
compared with the findLargest() method—provided that both objects are
of the same class.
What does this mean? Does this mean anything that implements Relatable can call findLargest()? If it's so, why does it say provided that both objects are of the same class?
----- EDIT -----
From the previous chapters of this tutorial:
Definition of relatable:
public interface Relatable {
// this (object calling isLargerThan)
// and other must be instances of
// the same class returns 1, 0, -1
// if this is greater // than, equal
// to, or less than other
public int isLargerThan(Relatable other);
}
Using relatable as a type:
public Object findLargest(Object object1, Object object2) {
Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ((obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2;
}
----- EDIT 2 -----
In the chapter on anonymous classes, it does this:
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
.
.
.
HelloWorld englishGreeting = new EnglishGreeting();
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
So how does this work?
the line Relatable obj1 = (Relatable)object1; seems to create an object of type Relatable
No. This line creates a reference (obj1) of type Relatable and assigns it to object1. In order for this to work, object1 has to be cast to the (interface) type Relatable.
No new objects are being created here.
Does this mean anything that implements Relatable can call findLargest()?
Yes.
If it's so, why does it say provided that both objects are of the same class?
It has to do with the implementation of isLargerThan(). Since any class implementing the Relatable interface can't know anything about other classes implementing it, they can't do meaningful comparisons with other classes. Therefore, in order for this to work, both objects need to be of the same class.
Response to EDIT 2
So how does this work?
Instead of first defining a class and then creating an instance of it, as in the case with the EnglishGreeting, the frenchGreeting is created on the fly. What happens under the cover is that a new class implementing HelloWorld is created, just like in the english case, only this time it is anonymous (you never get to give it a name). It is just a convenience shortcut for those times when you need a one-time implementation of an interface.
Interface types belong to the category of reference types in java. You can never instantiate an interface, but it can be assigned references to any of the objects of classes which implement it:
A variable whose declared type is an interface type may have as its
value a reference to any instance of a class which implements the
specified interface.
Interfaces are like behaviors. If a class happens to implement an interface, lets say Serializable, this adds a behavior to the class, which is, the class can be serialized.
This helps you introduce abstraction in your code. For example lets assume that you need a method in one of your utility classes which will be responsible for the actual job of serialization. Without interfaces you will end up writing a lot of methods, one for each object type that you want to serialize. Now imagine if you asked each of those objects to take care of their serialization themselves (by implementing a serialize method declared in the interface they implemented). With such implementation you need to write only one utility method for serialization. This method can take an argument of Serializable type, and instances of any class implementing this interface can be passed to the method. Now within the method you only need to invoke the serialize method on the interface variable. At runtime this will result in actual object's serialize method getting invoked.
Hope I was able to keep it simple.
Interface in Java is a mutual structure for classes that implement the interface, so the classes benefit from the methods/other member of that interface in their own way, which is called polymophism,
interface A
{
// method header only declared here, so implementation can vary between classes
public int foo();
}
class B implements A
{
public override String foo()
{
return "Class B";
}
}
class C implements A
{
public override String foo()
{
return "Class C";
}
}
so you can call foo() both from class B and C but they will react differently since they implement that method in their own way
An interface is just a class that defines the behaviour of an object, but not the underlaying implementation of it.
By making Relatable obj1 = (Relatable)object1; you are just casting the object1 to a Relatable type, and therefore you can call any of the methods defined in the Relatable interface
To your first question about Relatable obj1 = (Relatable)object1;:
A simple Relatable obj1; will not create an instance of Relatable, but specifies that any object assigned to it must be of a type implementing the Relatable-interface.
Therefore any object that is to be cast, must be of a type implementing the Relatable-interface.

Use a subclass object to modify a protected propety within its superclass object

Sorry for the crappy title I failed to think of a better version for my Java question.
I am right now using Java version: 1.6.0_18 and Netbeans version: 6.8
Now for the question.
What I've done is created a class with only one protected int property and next I made a public method to Set the int property to a given value.
Then I made an object of that class and used said public method to set the int property to 5.
Now I need your help to create another class that will take said object and expose it's protected int property.
The way I could think of doing this was to create a sub class to inherit said class and then create a method to Get the int property of the super class. I kind of succeeded to create the code to Get the int property but now I can't figure out how to use this new sub class to reference the object of the super class.
Here are the 2 classes I have thus far:
public class A
{
protected int iNumber;
public void setNumber ( int aNumber )
{
iNumber = aNumber;
}
}
public class B extends A
{
public int getNumber()
{
return super.iNumber;
}
}
I created an object of 'A' and used its method to set its property to 5, like this:
A objA = new A();
objA.setNumber ( 5 );
Now I want to create an object of 'B' to output the int stored within the property of 'objA'.
I've tried to run this code:
B objB = (B) objA;
String aNumber_String = String.valueOf( objB.getNumber() );
System.out.println( aNumber_String );
but I got the error: "java.lang.ClassCastException" on the first line B objB = (B) objA;
Please is there anyway of doing what I am trying to do?
P.S. I am hoping to make this idea work because I do not want to edit class A (unless I have no choice) by giving it a getter method.
P.P.S Also I know it's a 'bad' idea to expose the property instead of making it private and use public setter / getter methods but I like it this way :).
Edit: Added code tags
For the line
B objB = (B) objA;
the object of class A is not a object of class B, so that cast would not be allowed.
The class relationship between A and B is, that B is-a A, (because class B extends A), but the inverse cannot be said in this case.
Take the following for example, where the following exists:
class Animal.
class Dog extends Animal
What is being attempted in the above example is to cast an Animal to a Dog:
Dog dogObject = (Dog)animalObject; // Not allowed.
This cannot be necessarily the case, as not all Animals are Dogs -- for all we know, the animalObject could be an instance of the class Cat which extends Animal, which is definitely not a Dog.
You can't cast a A object to B. If you want to call getNumber, you must have a real B object:
B objB = new B();
objB.setNumber ( 5 );
System.out.println( objB.getNumber() );
No casts are necessary.
As others have said, you can't cast an A object to a B because of their relationship. What I'd add is that it really sounds like you only have one class, but you have some situations in which you want some other objects not to be able to read the value of the number. I'd say this is better served with an interface. Define the interface to only have the setNumber(int) method. Define the class to have both the getNumber() and the setNumber(int) methods, and to implement your "setter" interface. Then, wherever you have a method that accepts an A object as a parameter, change it to accept your interface.
This will allow you to have code that is not allowed to get the value of the object, but simplifies your code by only having one class defined.

What's the difference between calling MyClass.class and MyClass.getClass() [duplicate]

This question already has answers here:
What is the difference between a.getClass() and A.class in Java?
(7 answers)
Closed 7 years ago.
MyClass.class and MyClass.getClass() both seem to return a java.lang.Class. Is there a subtle distinction or can they be used interchangeably? Also, is MyClass.class a public property of the superclass Class class? (I know this exists but can't seem to find any mention of it in the javadocs)
One is an instance method, so it returns the class of the particular object, the other is a Class constant (i.e. known at compile-time).
Class n = Number.class;
Number o = 1;
o.getClass() // returns Integer.class
o = BigDecimal.ZERO;
o.getClass(); // returns BigDecimal.class
Both cases return instances of the Class object, which describes a particular Java class. For the same class, they return the same instance (there is only one Class object for every class).
A third way to get to the Class objects would be
Class n = Class.forName("java.lang.Number");
Keep in mind that interfaces also have Class objects (such as Number above).
Also, is MyClass.class a public property of the superclass Class class?
It is a language keyword.
.getClass() returns the runtime class of the object, so it can be modified when you change the class of the variable
.class on the other hand always return the class constant of the "Type"
NOTE
If the runtime class happens to be the same as the TYPE class, both will be equal.
Example:
Long x = new Long(2);
Class c1 = Long.class;
Class c2 = x.getClass();
//c1==c2
The MyClass doesn't have a static getClass method, in other words, you cannot call MyClass.getClass(), instead you need to call (new MyClass()).getClass() for it to work.
getClass() will return a MyClass.class object. So in other words, MyClass.class is the resulting object while getClass() is a method. The getClass() method is useful in cases where you do not know the actual class of the object, for example:
public void someMethod(Object o) {
if(o.getClass().equals(Set.class)) {
// The object is a set
} else if(o.getClass().equals(List.class)) {
// The object is a List
}
}
Note that the above code example isn't the best possible, I'm just trying to show how it could be used. The same functionality could be achieved with if(o instanceof Set) { ...}
What's the difference between calling MyClass.class and MyClass.getClass()
First of all your question title is a bit misleading! .getClass() is a method defined in java.lang.Object so any object in java can call it where as .class is called on the class itself(like public static variables). So the question should be (sticking to java naming conventions)
What's the difference between calling MyClass.class and myClassObject.getClass()
Now to actual differences
.getClass() is a native java method in java.lang.Object. This method will return java.lang.Class object corresponding to the runtime class of the object on which it is invoked. So
Test t = new TestSubClass();
Class c2 = t.getClass();
System.out.println(c2);
will print class TestSubClass
where as .class will return the statically evaluated (known at compile time) class. It is actually Class object corresponding to the reference type pointing to the actual object.So
Test t = new TestSubClass();
Class c2 = Test.class;
System.out.println(c2);
will print class Test

Categories

Resources