Override a private method in a Base class?
How can a subclass override a final method in its superclass.
This code compiles cleanly.
How is this possible?
Or Am I overlooking any point?
class MySuperClass{
private final String getMessage(){
return "hello";
protected String getAnotherMessage(){
return getMessage() + "world";
class MySubClass extends MySuperClass{
private final String getMessage(){
return "hi";
public String getAnotherMessage(){
return "anothermessage";
}
getMessage is declared as private in the base class, and therefor cannot be overridden in any subclass.
Edit: I think I understand the question better now. You want to know why it compiles when you think it shouldn't. It's because the private method isn't really inherited at all. Your subclass created a brand new private method of the same signature, but it's completely unrelated.
Similar Messages
-
How to access private method of an inner class using reflection.
Can somebody tell me that how can i access private method of an inner class using reflection.
There is a scenario like
class A
class B
private fun() {
now i want to use method fun() of an inner class inside third class i.e "class c".
Can i use reflection in someway to access this private method fun() in class c.I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
So here's what it looks like:
//list of inner classes, if any
Class[] classlist = A.class.getDeclaredClasses();
A outer = new A();
try {
for (int i =0; i < classlist.length; i++){
if (! classlist.getSimpleName().equals("B")){
//skip other classes
continue;
//this is what I mention above.
Constructor constr = classlist[i].getDeclaredConstructor(A.class);
constr.setAccessible(true);
Object inner = constr.newInstance(outer);
Method meth = classlist[i].getDeclaredMethod("testMethod");
meth.setAccessible(true);
//the actual method call
meth.invoke(inner);
} catch (Exception e) {
throw new RuntimeException(e);
Good luck, and if you find yourself relying on this too much, it might mean a code redesign. -
Hi,
We've got an abstract base class (StringBase) which various types of strings inherit from. The copy constructor for this base class is private, since we don't want to allow copying when this class shouldn't be directly instantiated. A number of our methods take specify the base class as a reference, but take a derived class temporary as a default argument (see code appended).
This worked fine in 12.3, but in 12.4 beta, this now says:
Error: StringBase::StringBase(const StringBase&) is not accessible from __dflt_argA().
This works fine in clang and gcc, and indeed, this GNU document says it was a bug which was fixed in gcc 4.3.0:
Copy constructor access check while initializing a reference
which references http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#391
It only appears to error when the "-g" option is used, however, which doesn't seem right, and compiles fine if the "-g" option is removed, which makes me think it's a bug. Presumably the optimizer is eliding the copy when not using -g, but it's left in for debug mode, causing the compile error?
Many thanks,
Jonathan.
$ clang++ -std=c++11 defaultarg.cpp
$ g++ -std=c++11 defaultarg.cpp
$ /opt/SolarisStudio12.4-beta_mar14-solaris-x86/bin/CC -c defaultarg.cpp
$ /opt/SolarisStudio12.4-beta_mar14-solaris-x86/bin/CC -g -c defaultarg.cpp
"defaultarg.cpp", line 6: Error: StringBase::StringBase(const StringBase&) is not accessible from __dflt_argA().
1 Error(s) detected.
$ cat defaultarg.cpp
#include "stringbase.h"
#include "conststring.h"
static const ConstString S_DEFAULT("default value");
void SomeMethod( const StringBase& str = S_DEFAULT )
(void) str;
int main( void )
SomeMethod();
$ cat stringbase.h
#ifndef STRINGBASE_H
#define STRINGBASE_H
class StringBase
protected:
StringBase() {}
private:
StringBase( const StringBase& );
#endif
$ cat conststring.h
#ifndef CONSTSTRING_H
#define CONSTSTRING_H
#include "stringbase.h"
class ConstString : public StringBase
public:
ConstString() {}
ConstString( const char* ) {}
ConstString( const ConstString& );
#endifThanks for reporting the problem!
This looks like a compiler bug, I think an artifact of creating a helper function for the debugger for the default argument.
I have filed bug 18505648 for you. -
Error while usind Private Method of a global class
HI All..
I created a global class (ZLINE_GLOBAL) which has TOT_DATA private method. I have to call this private method in my report, I know that using Friend class we can do this.
But it is not working and showing the same error " METHOD "TOT_DATA" is unknown or Private or Public..
code i tried is
CLASS c2 DEFINITION DEFERRED.
CLASS ZLINE_GLOBAL DEFINITION FRIENDS c2.
PUBLIC SECTION.
METHODS : m1.
PRIVATE SECTION.
METHODS: m2.
ENDCLASS.
CLASS ZLINE_GLOBAL IMPLEMENTATION .
METHOD m1.
WRITE : 'Public Method C1'.
ENDMETHOD. "M1
METHOD m2.
WRITE : 'Private Method C1'.
ENDMETHOD.
ENDCLASS.
CLASS c2 DEFINITION FRIENDS ZLINE_GLOBAL. "my friends are here, allow them access to my (C2's) private components
PUBLIC SECTION.
METHODS :m3.
ENDCLASS.
CLASS c2 IMPLEMENTATION.
METHOD m3.
DATA : obj TYPE REF TO ZLINE_GLOBAL.
CREATE OBJECT obj.
CALL METHOD obj->TOT_DATA. "here Iam calling Private method of global class
ENDMETHOD. "M3
ENDCLASS.
START-OF-SELECTION.
DATA obj_c2 TYPE REF TO c2.
CREATE OBJECT obj_c2.
obj_c2->m3( ).
can anybody help me on this..
MurthyHi Murthy,
Replace TOT_DATA with M2, you do not have any method by name "TOT_DATA" in your code.
CLASS c2 DEFINITION DEFERRED.
CLASS ZLINE_GLOBAL DEFINITION FRIENDS c2.
PUBLIC SECTION.
METHODS : m1.
PRIVATE SECTION.
METHODS: m2.
ENDCLASS.
CLASS ZLINE_GLOBAL IMPLEMENTATION .
METHOD m1.
WRITE : 'Public Method C1'.
ENDMETHOD. "M1
METHOD m2.
WRITE : 'Private Method C1'.
ENDMETHOD.
ENDCLASS.
CLASS c2 DEFINITION FRIENDS ZLINE_GLOBAL. "my friends are here, allow them access to my (C2's) private components
PUBLIC SECTION.
METHODS :m3.
ENDCLASS.
CLASS c2 IMPLEMENTATION.
METHOD m3.
DATA : obj TYPE REF TO ZLINE_GLOBAL.
CREATE OBJECT obj.
CALL METHOD obj->M2. "here Iam calling Private method of global class
ENDMETHOD. "M3
ENDCLASS.
START-OF-SELECTION.
DATA obj_c2 TYPE REF TO c2.
CREATE OBJECT obj_c2.
obj_c2->m3( ).
Regards,
Chen -
How to call a method of a base class if the base class is abstract...
This is my sample code>>>>
abstract class b {
public void display() {
System.out.println("I am in Base Class");
class test extends b {
public static void main(String[] args) {
test obj = new test();
obj.display();
public void display() {
System.out.println("I am in Derived Class");
I want to call base class version of display with derived class object.........is it possible....* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
* headdesk *
Enough with the friggin' zombie threads already! -
Creation of a static class with private methods
I'm new to java programming and am working on a project where I need to have a static class that does a postage calculation that must contain 2 private methods, one for first class and one for priority mail. I can't seem to figure out how to get the weight into the class to do the calculations or how to call the two private methods so that when one of my other classes calls on this class, it retrieves the correct postage. I've got all my other classes working correct and retrieving the information required. I need to use the weight from another class and return a "double". Help!!!
Here's my code:
* <p>Title: Order Control </p>
* <p>Description: Order Control Calculator using methods and classes</p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: Info 250, sec 001, T/TH 0930</p>
* @author Peggy Blake
* @version 1.0, 10/29/02
import javax.swing.*;
public class ShippingCalculator
static double firstClass, priorityMail;
//how do I get my weight from another class into this method to use??? not sure I understand how it works.
public static double ShippingCalculator(double weight)
String responseFirstClass;
double quantity, shippingCost;
double totalFirstClass, firstClass, priorityMail, totalShipping;
double priorityMail1 = 3.50d;//prioritymail fee up to 1 pound
double priorityMail2 = 3.95d;//prioritymail fee up to 2 pounds
double priorityMail3 = 5.20d;//prioritymail fee up to 3 pounds
double priorityMail4 = 6.45d;//prioritymail fee up to 4 pounds
double priorityMail5 = 7.70d;//prioritymail fee up to 5 pounds
quantity = 0d;//ititialization of quantity
// weight = 0d;//initialization of weight
// shippingCost = 0d;
//calculation of the number of items ordered..each item weights .75 ounces
quantity = (weight/.75);
if (quantity <= 30d)
//add 1 ounce to quantities that weigh less than 30 ounces
weight = (weight + 1);
else
//add 2 ounces to quantities that weigh more than 30 ounces
weight = (weight + 2);
if (weight > 80d)
//message to orderclerk ..order over 5 lbs, cannot process
JOptionPane.showMessageDialog(null, "Order exceeded 5 lbs, cannot process");
//exit system, do not process anything else
System.exit (0);
else
if (weight < 14d)
//send message to customer: ship firstclass or priority, y or n
responseFirstClass = JOptionPane.showInputDialog(null, "Ship first class? y or n?");
if (responseFirstClass.equals("y"))
//compute FirstClass shipping cost
totalFirstClass = ((weight - 1) * .23d) + .34d;
firstClass = totalFirstClass;
else
//compute PriorityMail cost for orders less than 14 ounces
priorityMail = (priorityMail1);
else
if (weight <=16d)
//compute totalshipping for orders up to 16 ounces
priorityMail = (priorityMail1);
else
if (weight <=32d)
//compute totalshipping for orders up to 32 ounces
priorityMail = (priorityMail2);
else
if (weight <=48d)
//compute totalshipping for orders up to 48 ounces
priorityMail = (priorityMail3);
else
if (weight <= 64d)
//compute totalshipping for orders up to 64 ounces
priorityMail = (priorityMail4);
else
//compute totalshipping for orders up to 80 ounces
priorityMail = (priorityMail5);
priorityMail = 0d;
firstClass = 0d;
firstClassMail ();
priorityMailCost ();
//I think this is where I should be pulling the two methods below into my code, but can't figure out how to do it.
shippingCost = priorityMail + firstClass;
return (shippingCost);
}//end method calculate shipping
private static double firstClassMail()//method to get first class ship cost
return (firstClass);
}//end method firstclass shipping
private static double priorityMailCost()//method to get priority mail cost
return (priorityMail);
}//end method priorityMail
}//end class shipping calculatorpublic class A {
public String getXXX () {
public class B {
A a = new A();
public void init () {
a.getXXX();
} -
Where to put methods in a abstract base class - subclasses system
Hi,
I’d like to ask a question on some basic design practice.
When there are methods which are common in some subclasses so I would like to “move them up” in the base abstract class, I would also like to make sure that the ADT concept of the base class itself is not broken. So I don’t want to have methods in the base class that are not general enough to be there. How to resolve this?
For example I create a base abstract class Vehicle. Then I create subclasses Plane and Tanker and realize that the startEnginge() method in them is the same and in order remove the duplicated code, I can put it in Vehicle. But later there may be Bicycle or Sled subclasses which don’t need startEngine().
In a broader sense, I would like to keep the Vehicle class as similar to the real word concept of vehicles as possible. And not evey vehicle have engine of course.
What is the solution?
Extending the class hierarchy by injecting another abstract class between the base and the subclasses? (e.g: VehicleWithEngine)
I suppose I can’t use Interfaces because I need to have the common implemenations as well.
Thanks for any comments in advance,
lemonboston
ps: I am a beginner and don't know the terminology, so if there are programming expression for the followings for example, I would be thankful if someone could help with this too:
- moving common methods up in the class hierarchy
- injecting a class in the hierarchy
- abstract base class - subclasses systemlemonboston wrote:
Hi,
I’d like to ask a question on some basic design practice.
When there are methods which are common in some subclasses so I would like to “move them up” in the base abstract class, I would also like to make sure that the ADT concept of the base class itself is not broken. So I don’t want to have methods in the base class that are not general enough to be there. How to resolve this?
You are talking about code.
Instead you need to talk about the design.
The base class represents conceptually a 'type' of something. That 'type' defines behavior. That behavior is what goes in the base class nothing else (in terms of design.)
If you have common functionality which does not fit into the definition (design) of the 'type' then you put it in another class and use (composition) that class in the sub class.
For example I create a base abstract class Vehicle. Then I create subclasses Plane and Tanker and realize that the startEnginge() method in them is the same and in order remove the duplicated code, I can put it in Vehicle. But later there may be Bicycle or Sled subclasses which don’t need startEngine(). No that is not how it works.
You have specific examples of some vehicles and then you need to manage those types generically. That is the first step.
Second step is then to determine what the exact 'type' is that you want to manage. And you use the requirements of the need to create the 'type'.
Then you look at the specific examples to determine how they will meet the needs of the type.
Thus if I have an application that must start the engines of all the vehicles in the city then I must have a vehicle class which has startEngine.
But if I have an application that manages vehicles as inventory (like a retail store) and then decide that because my examples both have engines that I might as well move it into the base class. In that case there is no 'need' for the application to manage starting vehicles. The fact that both have engines is irrelevant.
So looking back at your example you have stated functionality about your specific types but you have not stated anything about why your application needs to deal with that functionality generically.
Another way to think about it is that you do not put the shared functionality in the base because you can but rather because you must. -
Override a private() using reflection?
Please don't make me wrong - I know in OO normally you cannot override a private method.
Said that, I still have a scenario to do that, if possible. Basically, I have a 3rd party lib which has a class (approx. 1000 LOC) similar to following.
a) I just need to override one private class, if possible.
b) I do not want to copy&cut the whole class as there are too many private methods in it.
Any guru has a comment regarding the feasibility to employ the reflection?
TIA. WK
public class Base {
public void a() {
x1();
x2();
private void x1() {
y1();
private void y1() {} // I need to override this method, if possible.
}Reflection isn't going to help, because even if you declare an "overriding" method with the same signature (void y1()), the compiler and the JVM won't treat it as an overriding method. They will treat it as a different method from your Base class's y1() method and it won't be called polymorphically.
Sure, you can call the Base class's private y1() method using reflection, but my point is that you can't persuade code in the Base class to call your subclass's y1() method instead of its own. And that's what overriding would do. -
Are private methods inherently final?
You can�t override a private method, so is it inherently final? Will the compiler treat it like a final? I�ve heard that final methods may be inlined by the compiler but haven�t really been able to produce a test to show the advantage of inlining. I know in theory it trades speed for program size, but, if it does work, is it really that much faster? I�m guessing CPU local cache probably eliminates or at least reduces to negligible time the overhead of swapping out the instruction stack to perform a �jump.�
Thanks for your thoughts. Mostly trying to figure out when to use final methods.You can�t override a private method, so is it
inherently final? Given that that is exactly what the JLS says it would
suggest that the answer is yes.
http://java.sun.com/docs/books/jls/second_edition/html
/classes.doc.html#38958
I believe the invocation (byte code) is different as
well (but I didn't look it up) so the VM could
certainly easily do something with it.Actually, I don't think this is 100% accurate.
You can replace a private method in a subclass with the same signature (name, arg list) with the same return type. In fact, this is true even if the private method is declared final. It is only when the final method is public (maybe protected and package, I'm not sure) that the compiler complains when you try to extend it.
� {� -
How to call a private method in a JFrame
I have a Frame which has some properties like its size, bgcolor plus other parameters, as instance variables. There is a button on the Frame with the caption : "set properties". When one clicks on that button, a new frame should appear via which a user can change the values of the parameters of the main Frame (i.e size, bgcolor,..etc). The user would input the new values in the textfields or radio buttons that are on the new frame, and then click a submit button, which has to exist on the same NFrame. How can I do that so that when the submit button is pressed, the parameters values are updated and so is the display view ?
I made it this way : I created 2 classes, the main frame and the new Frame. I made the new Frame an instance variable of the main Frame. When the user clicks the " set properties" button on the main Frame, the new Frame is shown. The user enters new values for some of the parameters and clicks submit. The parameters in the new Frame are updated. UP TO HERE EVERYTHING WENT JUST FINE. Now, there is a private method in the main frame that changes the color, size, ...etc of the main frame according to the values stored in the instance variables color, size,...etc. THE QUESTION IS: How can the new Frame display the changes after the values have been updated ? That is, how can it call the "private" method in the main class?? Should the new class be a child class of the main class to be able to access it's private methods ??import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class CallingHome
SkinMod skinMod;
JPanel panel;
public CallingHome()
// send reference so SkinMod can call methods in this class
skinMod = new SkinMod(this);
JButton change = new JButton("change properties");
change.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
skinMod.showDialog();
JPanel north = new JPanel();
north.add(change);
panel = new JPanel();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(north, "North");
f.getContentPane().add(panel);
f.setSize(300,100);
f.setLocation(200,200);
f.setVisible(true);
public void setBackground(Color color)
panel.setBackground(color);
panel.repaint();
public static void main(String[] args)
new CallingHome();
class SkinMod
CallingHome callHome;
Random seed;
JDialog dialog;
public SkinMod(CallingHome ch)
callHome = ch;
seed = new Random();
createDialog();
public void showDialog()
if(!dialog.isShowing())
dialog.setVisible(true);
private void createDialog()
JButton change = new JButton("change background");
change.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
callHome.setBackground(getColor());
dialog.dispose();
JPanel p = new JPanel();
p.add(change);
dialog = new JDialog();
dialog.getContentPane().add(p);
dialog.setSize(200,100);
dialog.setLocation(525,200);
private Color getColor()
return new Color(seed.nextInt(0xffffff));
} -
We have entity classes that we use to access our database. We have subclasses derived from these entity classes that apply business rules. For instance, the base class AddressEntity has a
setAddress2(string) that AddressEntity.select() uses to set a class variable with data retrieved from the database. The derived class Address also has a setAddress2(string) method that puts restrictions on the length of the data. I want the AddressEntity.select() method to use the base class method AddressEntity.setAddress2(). I've tried using this.setAddress2() in AddressEntity.select() but the derived class method is still used. Any suggestions?
Thanks,
JoeIf you need to call some methods on the base class sometimes and some methods on the derived class other times, but using the same object, then yes dubwai is right you should revisit your Object hierarchy.
One simple way to do what you are asking is to have your method(s) look like this:
void setAddress2(String sAddress) { setAddress2(sAddress, true); }
void setAddress2(String sAddress, boolean bRestrictLength) {
// real method
}then you could just look at the variable bRestrictLength to see if you need to restrict the length, and have it default to true. In this way you can use overloading to solve your problem. -
Overloaded methods in a derived class
Hello to everyone. I'm starting to learn java with the help of "Thinking in Java". I just want something to make it clearer for me.
Suppose I have a base class with a method, and a derived class which overloads the method:
class Base {
void method() {
System.out.println("Base method");
class Derived extends Base {
void method() {
System.out.println("Derived method");
}Now, in another class somewhere I create an instance of Derived:
Derived dv = new Derived();
dv.method();There is no way that I can access the method from the Base class, right? The only way I can do that is through
class Derived extends Base {
void method() {
super();
System.out.println("Derived method");
}As I said, I'm almost sure that this is correct, I just want a confirmation.You can change the class
class Derived extends Base {
void method() {
super.method();
System.out.println("Derived method");
// calls Base.method()
void baseMethod() {
super.method();
} -
What is the best way to handle the instantiation of a derived class from an existing base class.
I have a base class which is being created via remote_object [RemoteClass alias] from the server. I have other specialized classes that are derived from this baseclass, but serialization with the server always happens with the base class. The base class has meta data that defines what the derived class is, for example
[RemoteClass (alias="com.myco...')]
public Class Base
public var derivedType:String;
public function Base()
public Class Derived extends Base
public "some other data"
public function Derived()
In my Cairgorm command which retrieves this object from ther server I want to do this:
public function result (event: Object):void
var baseInstance:Base = event.result;
if (baseInstance.derivedType = "derived")
var derivedInstance:Derived = new Derived( baseInstance );
What is the most efficient way of doing this? It appears to me that doing a deep-copy/clone and instantiation of the derived class is pretty inefficient as far as memory allocation and data movement via the copy.Thanks for the assistance. Let me try to clarify.
MY UI requires a number of composite classes. The individual components of the composite classes are being transfered to/from the server at different times depending upone which component has changed state. The construction of the composite classes from the base class happens in my clients business logic.
Composition happens in a derived class; but server syncronization happens using the base class. When I recieve the object from Blazeds through the remote object event, it is in the form of the base class. I then need to instantiate the derived class and copy the elements of the base class into it (for later composite construction). And likewise when sending the base class back to the server, I need to upcast the derived class to its base class. But in this case just a mere upcast does not work. I actually need to create a new base class and copy the attrbutes into it. I believe this is limitation of how remoting works on Flex/AS3.
My question is, what is the best way to turn my base class into it's derived class so further composite construction can take place. The way I am currently doing it is to create a load method on the base class, that takes the base class as on argument. The load function, copies all of the instance attribute references from the base class to the target class.
public Class Base
public function Base()
public function load(fromClass:Base)
{ // copy the references for all of the instance attributes from the fromClass to this class }
Then, after I recieve the base class from the server. I create a new derived class and pass the base class into the load function like this:
for (var i:int=0; i < event.result.length; i++) {
var derived:Derived = new Derived();
derived.load(event.result[i]);
The drawbacks of this approach is that it now requires 2 extra instance creations per object serialization. One on recieving the object from the server and one sending it to the server. I assume copying references are pretty efficient. But, there is probably some GC issues. The worst of it is in code maintenance. The load function now has to be manually maintained and kept in sync with the server class.
It would be interesting to hear how others have solved this problem. The server side is an existing application with around 2M LOC, so changing the code on the server is a non-starter.
Thanks for your help. -
NewInstance & constructor of base class
When I instantiate a sub class directly (using new), the code in the constructor method of both base and sub classes run.
When I instantiate using java.lang.reflect.Constructor.newInstance, only the sub class's constructor method is invoked. Is there a way to force running the constructor method of the base class as well?
Thanks & Regards.when I tried to build a simple code to show the problem, I realised that the problem is somewhere else - Still not solvable by me - Please help.
Irrespective of whether new or Constructor.newInstance -
The constructor method with appropriate signature is invoked from child class.
The constructor method without any arguments is invoked from parent class. - This is the reason for my original problem.
In the attached code, the variable xyz is not getting assigned proper value (from the argument a).
public class Mainer {
public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, java.lang.reflect.InvocationTargetException
int inArg = 5;
System.out.println("With new");
ChldClass chld1 = new ChldClass(inArg);
chld1.m1();
System.out.println("With Constructor.newInstance");
java.lang.reflect.Constructor ArgsConstructor;
Class[] argsClass = new Class[] {int.class};
Class chld2Class = Class.forName("ChldClass");
ArgsConstructor = chld2Class.getConstructor(argsClass);
Object[] argsObject = new Object[] {5};
ChldClass chld2 = (ChldClass)ArgsConstructor.newInstance(argsObject);
chld2.m1();
class PrntClass
int xyz;
public PrntClass(int a)
xyz = a;
System.out.println("Int Arg Constructor within Parent Class <<<" + xyz + ">>>");
public PrntClass()
System.out.println("Default Constructor within Parent Class");
public void m1()
System.out.println("M1 of Parent Class");
class ChldClass extends PrntClass
public ChldClass(int a)
System.out.println("Int Arg Constructor within Child");
public void m1()
System.out.println("Value of xyz "+xyz);
public void m2()
System.out.println("M2 of ChldClass");
The result displayed:
With new
Default Constructor within Parent Class
Int Arg Constructor within Child
Value of xyz 0
With Constructor.newInstance
Default Constructor within Parent Class
Int Arg Constructor within Child
Value of xyz 0
Thanks & Regards. -
ABAP Objects: Calling private Methods
Hi,
i would choose an private Method of an global class (for example class: CL_GUI_ALV_GRID private Method: SEARCH_START) in a local class.
class lcl_test definition for testing.
private section.
methods test for testing.
data ref_alv type ref to cl_gui_alv_grid.
endclass.
class lcl_test implementation.
method for test.
create object ref_alv ...
* How to call a private Method?
call method ref_alv->search_start( ). "not possible!
endmethod.
endclass.
Is this possible?
Regards,
DamirDamir, of course you can call a private method of a class, if this class has made you a friend with the syntax element FRIENDS (available since Release 6.10). Here is a syntactically correct example, when my_method is a private class method:
REPORT test.
CLASS mytest DEFINITION FOR TESTING.
PRIVATE SECTION.
METHODS test FOR TESTING.
ENDCLASS.
CLASS myclass DEFINITION FRIENDS mytest.
PUBLIC SECTION.
CLASS-METHODS my_method.
ENDCLASS.
CLASS myclass IMPLEMENTATION.
METHOD my_method.
ENDMETHOD.
ENDCLASS.
CLASS mytest IMPLEMENTATION.
METHOD test.
CALL METHOD myclass=>my_method.
ENDMETHOD.
ENDCLASS.
If my_method is not a class method, then you need to create an object of the class first, whose methods you want to test.
Kind regards,
Michael Kraemer
Maybe you are looking for
-
Hi We are running on SharePoint Server 2013.When we add AD groups as permissions, we see that the group name is being displayed properly in the permissions. Whereas when I click on the groupname I see the SID with the Sharepoint specific claims chara
-
PhotoStream: it will not let me set it up to on my iMac
After using my iPad 2 and iPhone 4s I thought I'd replace my Windows 7 PC and get an iMac 21.5, which I did and have been mostly happy with it. However, the Photo Stream in iPhoto did not show my photos from the other two mobile devices. After much
-
Using unix remsh in BR*tools Studio
Hi I have installed BR*tools Studio on Unix for Multi-instance server mode purpose. The probelm is how to connect the Oracle instances to this server . For that I need the corret parameter line needed when creatine an instance in the BR*tools Studio
-
Payment made outside SAP and need to maintain the record in the system.
Hi Experts, Please help me with this. A payment was made outside the SAP System but, need to be updated in the SAP for record purpose without paying again. Is there is way we can do it? Thanks in Advance Dip
-
Solaris 11 hp dl 180 g6 - installer doesn't start
Hi. I'm trying to install solaris 11 on an hp dl 180 g6 server. My main problem is that the installer cannot start - after 'Preparing disk image for use' I got 'Login services cabbot run' and it starts the maintenance mode. In this maintenance mode I