Variable in derived class more public
Hello,
I thought variables in a derived class could not be more public than the variables they hide (in the base class) e.g. the "var" variable in "DerivedDemo" could not be more public than the "var" variable in Demo. (which would be the opposite to methods) Am I right?
class Demo {
private int var;
class DerivedDemo extends Demo{
public int var;
}Thanks in advance,
Balteo.
actually, you'll find you get to variables:
class abc extends z {
public int k = 20;
public abc(){
System.out.println("k from abc: " + k);
public static void main(String[] args){
abc z = new abc();
System.out.println("mm: " + z.k);
System.out.println("mm: " + z.getK());
z.test();
class z {
private int k = 2;
public void test(){
System.out.println("k from z: " + k);
public int getK(){ return k; }
};)
Similar Messages
-
Accessing super class private variables from derived class
posted November 01, 2005 08:20 PM Profile for kenji mapes Email kenji mapes Send New Private Message Edit/Delete Post Reply With Quote Assume I have a default and a param constructor in both a subclass and a super class. The members are private.
So after validation logic in the sub class param. constructor, I want to access an instance variable of the super class's default constructor to set the subclass's matching variable to the default in the super class.
Is there anyway I can do this. Of course, I have inherited setters and getters.
Thanks.posted November 01, 2005 08:20 PM Profile for
kenji mapes Email kenji mapes Send New Private
Message Edit/Delete Post Reply With QuoteI suppose this is the result of an attempted crossposting from another forum. :) -
How to use Public variables in other classes
Please have a look at the program.
In the below program, i want to use the variable 'name' in the class cl_airplane1 implementation under the method aircraft to display 'BRITISH AIRWAYS' which i am passing through the object AIR1.
The variable 'name' is declared under public section of the class cl_airplane. I do not want to use inheritance. Can i do this.
*& CLASS DEFINITION
CLASS cl_airplane DEFINITION.
PUBLIC SECTION.
METHODS set IMPORTING im_name TYPE string
im_weight TYPE i.
METHODS display.
DATA name TYPE string.
PRIVATE SECTION.
DATA weight TYPE i.
ENDCLASS.
*& CLASS IMPLEMENTATION
CLASS cl_airplane IMPLEMENTATION.
*******METHOD SET*****************
METHOD set.
name = im_name
weight = im_weight.
ENDMETHOD.
*******METHOD DISPLAY**************
METHOD display.
WRITE : / ' NAME :', name, ' AND ', 'WEIGHT:', weight.
ENDMETHOD.
ENDCLASS.
*& END OF CLASS CL_AIRPLANE IMPLEMENTATION
*& CLASS DEFINITION-CL_AIRPLANE1
CLASS cl_airplane1 DEFINITION .
PUBLIC SECTION.
METHODS : aircraft IMPORTING im_name1 TYPE string,
dis1.
ENDCLASS.
*& CLASS IMPLEMENTATION
CLASS cl_airplane1 IMPLEMENTATION.
*******METHOD AIRCRAFT
METHOD aircraft.
ENDMETHOD.
********METHOD DIS1
METHOD dis1.
ENDMETHOD.
ENDCLASS.
**********CREATING REFERENCE VARIABLES
DATA : air TYPE REF TO cl_airplane.
DATA : air1 TYPE REF TO cl_airplane1.
START-OF-SELECTION.
***CREATING AN OBJECT OF THE CLASS CL_AIRPLANE
CREATE OBJECT air .
CALL METHOD air->set
EXPORTING
im_name = 'Lufthansa'
im_weight = '1000'.
CALL METHOD air->display.
***CREATING AN OBJECT OF THE CLASS CL_AIRPLANE1
CREATE OBJECT air1.
CALL METHOD air1->aircraft
EXPORTING
im_name1 = 'BRITISH AIRWAYS'.
CALL METHOD air1->dis1.
<removed_by_moderator>
Thanks.
Edited by: Julius Bussche on Jul 30, 2008 3:13 PMHere is ur solution:
*& Report Z157780_PRG1
REPORT z157780_prg1.
*& CLASS DEFINITION
CLASS cl_airplane DEFINITION.
PUBLIC SECTION.
METHODS set IMPORTING im_name TYPE string
im_weight TYPE i.
METHODS display.
DATA name TYPE string.
PRIVATE SECTION.
DATA weight TYPE i.
ENDCLASS. "
*& CLASS IMPLEMENTATION
CLASS cl_airplane IMPLEMENTATION.
********METHOD SET******************
METHOD set.
name = im_name.
weight = im_weight.
ENDMETHOD. "set
********METHOD DISPLAY***************
METHOD display.
WRITE : / ' NAME :', name, ' AND ', 'WEIGHT:', weight.
ENDMETHOD. "display
ENDCLASS. "
*& END OF CLASS CL_AIRPLANE IMPLEMENTATION
*& CLASS DEFINITION-CL_AIRPLANE1
CLASS cl_airplane1 DEFINITION INHERITING FROM cl_airplane.
PUBLIC SECTION.
METHODS : aircraft IMPORTING im_name1 TYPE string,
dis1.
ENDCLASS. "
*& CLASS IMPLEMENTATION
CLASS cl_airplane1 IMPLEMENTATION.
*******METHOD AIRCRAFT
METHOD aircraft.
name = im_name1.
WRITE : / ' NAME :', name.
ENDMETHOD. "aircraft
********METHOD DIS1
METHOD dis1.
ENDMETHOD. "dis1
ENDCLASS. "
**********CREATING REFERENCE VARIABLES
DATA : air TYPE REF TO cl_airplane.
DATA : air1 TYPE REF TO cl_airplane1.
START-OF-SELECTION.
***CREATING AN OBJECT OF THE CLASS CL_AIRPLANE
CREATE OBJECT air .
CALL METHOD air->set
EXPORTING
im_name = 'Lufthansa'
im_weight = '1000'.
CALL METHOD air->display.
***CREATING AN OBJECT OF THE CLASS CL_AIRPLANE1
CREATE OBJECT air1.
CALL METHOD air1->aircraft
EXPORTING
im_name1 = 'BRITISH AIRWAYS'.
CALL METHOD air1->dis1.
Hope That Helps
Anirban M. -
Accessing public variables from other classes
Probably a simple questions, but how can I access a variable from another class. My exact situation is as follows.
A class called WorldCalender has a variable which is defined: public int hour; (the value is given to it elsewhere).
I want to access this variable and increase it by one in a subroutine in the class Hour. In this class I have put: WorldCalender.hour++; but it doesn't seem to work. How should I do it?don't expose the hour variable at all.
have a method eg addToHourBy( int hrs )
Probably a simple questions, but how can I access a
variable from another class. My exact situation is as
follows.
A class called WorldCalender has a variable which is
defined: public int hour; (the value is given to it
elsewhere).
I want to access this variable and increase it by one
in a subroutine in the class Hour. In this class I
have put: WorldCalender.hour++; but it doesn't seem to
work. How should I do it? -
SQLJ compile failure in derived class
I have successfully comiled and run the "SimpleExample" defined
in the Help Topics "Developing Applications Using SQLJ" page.
However, if I make a simple modification to make the class
derived from another class (DoNothing class shown below is the
simplest case I've tried) I get compilation errors:
Error (52) Illegal INTO ... bind variables list: illegal
expression..
Error (0) SQLJ translation aborted.
Error (0) sqlj.framework.TranslationException. Error occured in
SQLJ translation.
Modified SimpleExample looks like:
public class SimpleExample extends DoNothing {
......as before
where DoNothing is defined as:
package RDBInterface; // My SimpleExample is in same package
public class DoNothing {
public DoNothing() {
Any ideas about this?
nullAndy,
I got the answer to that in another thread,
cheers Jon
Re: SQLJ-Problem with JDeveloper 2.0
From: Chris Stead (guest)
Email: [email protected]
Date: Tue Feb 02 13:07 CST 1999
Markus Rosenkranz (guest) wrote:
: Hi,
: I tried to rebuild an SQLJ-file with the new JDev. 2.0.
Whenever
: there is an iterator definition in a derived class compilation
: failed. By removing the extends clause in the class definition
: the compilation error could be avoided. It seems that the
: iterator definition is ignored. With JDev. 1.1 everthing
worked
: fine. How can this problem be solved.
: TIA Markus
Hi Markus,
Your question seems similar to the one that was just resolved.
Here are the specifics:
I'm using the production SQLJ and getting a frustrating error
of:
-- "Left hand side of assignment does not have a Java type."
I've reduced my testcase down to the absolute
minimum, but maybe I'm missing something obvious...
package oracle.xml.website;
import java.sql.SQLException;
import javax.servlet.http.*;
#sql iterator empiter ( String empname );
public class WebXSL extends HttpServlet {
public void foo() throws SQLException {
empiter myEmps = null;
#sql myEmps = {SELECT ename empname from EMP order by sal
desc };
Hi,
Could you please check whether the class HttpServlet is
available
in your CLASSPATH? The type resolver could be failing to find
this class in the process of looking for the definition of
'empiter', which is the type of your iterator variable myEmps.
The error message is somewhat obscure, we will be working on
improving it..
The SQLJ translator does a full type resolution of Java
variables
and expressions used in #sql statements, following JLS rules of
scoping and precedence for class and interface hierarchies. It
looks for classes in the CLASSPATH, as well as in the .sqlj and
.java source files specified on the sqlj command-line. So, if
you have .sqlj and .java files that are mutually dependent, you
could do:
sqlj Foo.sqlj Bar.java
Please let us know if your problem persists.. and see also bug
801780 for a related discussion.
- Julie
Julie,
Your suggestion helped! Thanks.
With 20/20 hindsight now, it would have been much more
helpful if the SQLJ translator reported an error message like:
-> Left hand side of assignment is not a Java type.
-> Unable to resolve class "HttpServlet". Check CLASSPATH
That would have keyed me into the problem many hours ago :-)
You suggestion lead me to test sqlj-ing my testcase
both outside and inside the JDeveloper environment.
Outside the environment, if I make sure J:\lib\jsdk.jar is
in my classpath, then all is well.
Inside the environment, I had included the named
library for "JavaWebServer" in my project libraries
and its classpath info was properly set to J:\lib\jsdk.jar,
but it appears that somehow JDev is not properly passing
this project-level classpath info to the SQLJ translator.
I was able to solve my problem (a hack!) by adding
J:\lib\jsdk.jar
to the:
IDEClasspath=
setting in the J:\bin\jdeveloper.ini file which I shouldn't
have to do. I filed Bug 813116 for the JDev team.
null -
Warning :: Derived class hides the base class virtual function
We are porting from CC5.3 to CC5.8 compiler with Sun Studio one compiler. After plenty of hurdles we are in the final stage of removing the warning messages... Amoung the plenty the following one is very common and in different files. Why am I getting this error in 5.8 and not in 5.3 compiler....
Warning: derived_Object::markRead Hides the virtual function base_Object::markRead(ut_SourceCodeLocation&) const in a virtual base
From this it is easily understandable that the base class mark read was hidden by derived class markRead... when we drive and override the derived class function.... It is all over the place....
Thank you,
Saravanan Kannan
//public: using xx_Object :: markRead;
virtual void markRead() const;The Sun C++ FAQ discusses the warning message:
http://developers.sun.com/prodtech/cc/documentation/ss11/mr/READMEs/c++_faq.html#Coding1
Notice that warnings are not necessarily errors. But I applaud your desire to fix the code so that it generates no warnings. I wish more of our customers could be persuaded to do the same. :-)
C++ 5.3 issues this warning, by the way. Example:
struct B { virtual int foo(int); };
struct D : B { virtual int foo(double); }; // line 2
D d;
line 2: Warning: D::foo hides the virtual function B::foo(int).
If for your particular code you do not see a warning with C++ 5.3, it would be due to a bug in C++ 5.3 that was later fixed. -
Almost there. Can't driver doesn't recognize variables in another class?
I know this has got to be an easy fix.. but i can't figure it out.so I'll put it all here... it's a program that serves as inventory. add items. sell items. etc...
this driver will not compile while the item and inventory classes compile fine.
// Project7BDriver.java
import java.util.Scanner;
public class Project7BDriver
public static void main( String[] args )
//Start Scanner to take input
Scanner scan = new Scanner( System.in );
//instantiate an Inventory
Inventory myInventory = new Inventory(3);
//find choice and continue until user quits
int userChoice = 0;
while( userChoice != 4 )
menu();
userChoice = scan.nextInt();
public static void menuSwitch( int choice, Inventory myInventory )
//Start Scanner to take input
Scanner scan = new Scanner( System.in );
switch( choice )
//user possibilities
case 1:
System.out.print("Enter name of item to be added: ");
itemName = scan.next();
System.out.print("Enter id of item to be added: ");
itemId = scan.nextInt();
System.out.print("Enter quantity of item to be added: ");
quantityInStock = scan.nextInt();
System.out.print("Enter suggest retail value of item to be added: $");
suggestedRetailValue = scan.nextDouble();
myInventory.addNewItemToInventory(itemName, itemId, quantityInStock, suggestedRetailValue);
break;
case 2:
System.out.print( inventory.toString() );
break;
case 3:
System.out.print("Enter id of item to be sold: ");
identification = scan.nextInt();
System.out.print("Enter quantity of item to be sold: ");
sellQuantity = scan.nextInt();
inventory.sellItem(identification, sellQuantity);
case 4:
System.out.println("\nGoodbye!");
break;
default:
System.out.println("Sorry, invalid choice");
public static void menu()
System.out.println("\nInventory");
System.out.println("*********");
System.out.println("1: Add item to inventory");
System.out.println("2: Print inventory");
System.out.println("3: Sell item");
System.out.println("4: Quit");
System.out.print("\nEnter your choice: ");
import java.text.NumberFormat;
public class Inventory
//INSTANCE VARIABLES
private Item[] items;
private double totalInventoryValue;
private int numOfItemsInInventory;
//CONSTRUCTOR
public Inventory( int capacity )
items = new Item[capacity];
totalInventoryValue = 0.0;
numOfItemsInInventory = 0;
//METHODS
public void increaseArraySize()
Item[] temp = new Item[items.length + 3];
for (int i = 0; i<items.length; i++)
temp[i] = items;
items = temp;
public void addNewItemToInventory (String itemName, int itemId, int quantityInStock,
double suggestedRetailValue)
if (numOfItemsInInventory == items.length)
increaseArraySize();
items[numOfItemsInInventory] = new Item (itemName, itemId, quantityInStock,
suggestedRetailValue);
numOfItemsInInventory++;
totalInventoryValue = totalInventoryValue + suggestedRetailValue*quantityInStock;
public void sellItem(int identification, int sellQuantity)
int indexItem = -1;
for (int j =0; j<numOfItemsInInventory; j++)
if(items[j].getID() == identification)
indexItem = j;
if(indexItem == -1)
System.out.println("The item you are searching for could not be found.\n " +
"Sale not completed.");
else
if(sellQuantity > items[indexItem].getQuantity())
System.out.println("It is not possible to buy more items than we have in stock.\n" +
"Sale not completed.");
else
totalInventoryValue -= items[indexItem].getValue()*sellQuantity;
numOfItemsInInventory -= sellQuantity;
public String toString()
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String result = "Item ID\t\tItem Name\t\tItem Quantity\t\tRetail Value";
result += "\n-------\t\t---------\t\t-------------\t\t------------";
for( int i = 0; i < numOfItemsInInventory; i++ )
result += "\n" + items[ i ];
result += "\n\nTotal value of inventory: " + fmt.format( totalInventoryValue );
return result;
} import java.text.NumberFormat;
public class Item
//INSTANCE VARIABLES
//name of item
private String itemName;
//id of item
private int itemID;
//present quantity of item in stock
private int quantityInStock;
//suggested price for item
private double suggestedRetailValue;
//CONSTRUCTOR
public Item( String name, int id, int quantity, double value )
itemName = name;
itemID = id;
quantityInStock = quantity;
suggestedRetailValue = value;
//CLASS GETTERS
public String getName()
return itemName;
public int getID()
return itemID;
public int getQuantity()
return quantityInStock;
public double getValue()
return suggestedRetailValue;
//CLASS SETTERS
public void setName( String name )
itemName = name;
public void setID( int id )
itemID = id;
public void setQuantity( int quantity )
quantityInStock = quantity;
public void setValue( double value )
suggestedRetailValue = value;
//TOSTRING method
public String toString()
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String result = "" + itemID + "\t\t\t" + itemName + "\t\t" + quantityInStock + "\t\t\t" + fmt.format( suggestedRetailValue );
return result;ahhh okay thanks a whole lot!!one more thing.. everything compiles.. but i can't figure a few things out.. even after debugging..when i add items to inventory.. it has null in the list of items...also.. I'm just having trouble with selling items.. here'e the code. if someone could run it and explain how to correct the errors that would be great
import java.util.Scanner;
public class Project7BDriver
public static void main( String[] args )
//Start Scanner to take input
Scanner scan = new Scanner( System.in );
//instantiate an Inventory
Inventory myInventory = new Inventory(3);
//find choice and continue until user quits
int choice = 0;
while( choice != 4 )
menu();
choice = scan.nextInt();
menuSwitch(choice, myInventory);
public static void menuSwitch( int choice, Inventory myInventory )
//Start Scanner to take input
Scanner scan = new Scanner( System.in );
switch( choice )
//user possibilities
case 1:
System.out.print("Enter name of item to be added: ");
String itemName = scan.next();
System.out.print("Enter id of item to be added: ");
int itemId = scan.nextInt();
System.out.print("Enter quantity of item to be added: ");
int quantityInStock = scan.nextInt();
System.out.print("Enter suggest retail value of item to be added: $");
double suggestedRetailValue = scan.nextDouble();
myInventory.addNewItemToInventory(itemName, itemId, quantityInStock, suggestedRetailValue);
break;
case 2:
System.out.print( myInventory.toString() );
break;
case 3:
System.out.print("Enter id of item to be sold: ");
int identification = scan.nextInt();
System.out.print("Enter quantity of item to be sold: ");
int sellQuantity = scan.nextInt();
myInventory.sellItem(identification, sellQ2uantity);
break;
case 4:
System.out.println("\nGoodbye!");
break;
default:
System.out.println("Sorry, invalid choice");
public static void menu()
System.out.println("\nInventory");
System.out.println("*********");
System.out.println("1: Add item to inventory");
System.out.println("2: Print inventory");
System.out.println("3: Sell item");
System.out.println("4: Quit");
System.out.print("\nEnter your choice: ");
import java.text.NumberFormat;
public class Item
//INSTANCE VARIABLES
//name of item
private String itemName;
//id of item
private int itemID;
//present quantity of item in stock
private int quantityInStock;
//suggested price for item
private double suggestedRetailValue;
//CONSTRUCTOR
public Item( String name, int id, int quantity, double value )
itemName = name;
itemID = id;
quantityInStock = quantity;
suggestedRetailValue = value;
//CLASS GETTERS
public String getName()
return itemName;
public int getID()
return itemID;
public int getQuantity()
return quantityInStock;
public double getValue()
return suggestedRetailValue;
//CLASS SETTERS
public void setName( String name )
itemName = name;
public void setID( int id )
itemID = id;
public void setQuantity( int quantity )
quantityInStock = quantity;
public void setValue( double value )
suggestedRetailValue = value;
//TOSTRING method
public String toString()
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String result = "" + itemID + "\t\t\t" + itemName + "\t\t" + quantityInStock + "\t\t\t" + fmt.format( suggestedRetailValue );
return result;
import java.text.NumberFormat;
public class Inventory
//INSTANCE VARIABLES
private Item[] items;
private double totalInventoryValue;
private int numOfItemsInInventory;
//CONSTRUCTOR
public Inventory( int capacity )
items = new Item[capacity];
totalInventoryValue = 0.0;
numOfItemsInInventory = 0;
//METHODS
public void increaseArraySize()
Item[] temp = new Item[items.length + 3];
for (int i = 0; i<items.length; i++)
temp[i] = items;
items = temp;
public void addNewItemToInventory (String itemName, int itemId, int quantityInStock,
double suggestedRetailValue)
if (numOfItemsInInventory == items.length)
increaseArraySize();
items[numOfItemsInInventory] = new Item (itemName, itemId, quantityInStock,
suggestedRetailValue);
numOfItemsInInventory += quantityInStock;
totalInventoryValue = totalInventoryValue + suggestedRetailValue*quantityInStock;
public void sellItem(int identification, int sellQuantity)
int indexItem = -1;
for (int j =0; j<numOfItemsInInventory; j++)
if(items[j].getID() == identification)
indexItem = j;
if(indexItem == -1)
System.out.println("The item you are searching for could not be found.\n " +
"Sale not completed.");
else
if(sellQuantity > items[indexItem].getQuantity())
System.out.println("It is not possible to buy more items than we have in stock.\n" +
"Sale not completed.");
else
totalInventoryValue -= items[indexItem].getValue()*sellQuantity;
numOfItemsInInventory -= sellQuantity;
public String toString()
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String result = "Item ID\t\tItem Name\t\tItem Quantity\t\tRetail Value";
result += "\n-------\t\t---------\t\t-------------\t\t------------";
for( int i = 0; i < numOfItemsInInventory; i++ )
result += "\n" + items[ i ];
result += "\n\nTotal value of inventory: " + fmt.format( totalInventoryValue );
return result; -
How to load function from derived class from dll
Dear all,
how to access extra function from derived class.
for Example
//==========================MyIShape.h
class CMyIShape
public:
CMyIShape(){};
virtual ~CMyIShape(){};
virtual void Fn_DrawMe(){};
// =========== this is ShapRectangle.dll
//==========================ShapRectangle .h
#include "MyIShape.h"
class DLL_API ShapRectangle :public CMyIShape
public:
ShapRectangle(){};
virtual ~ShapRectangle(){};
virtual void Fn_DrawMe(){/*something here */};
virtual void Fn_ChangeMe(){/*something here */};
__declspec (dllexport) CMyIShape* CreateShape()
// call the constructor of the actual implementation
CMyIShape * m_Obj = new ShapRectangle();
// return the created function
return m_Obj;
// =========== this is ShapCircle .dll
//==========================ShapCircle .h
#include "MyIShape.h"
class DLL_API ShapCircle :public CMyIShape
public:
ShapCircle(){};
virtual ~ShapCircle(){};
virtual void Fn_DrawMe(){/*something here */};
virtual void Fn_GetRadious(){/*something here */};
__declspec (dllexport) CMyIShape* CreateShape()
// call the constructor of the actual implementation
CMyIShape * m_Obj = new ShapCircle();
// return the created function
return m_Obj;
in exe there is no include header of of ShapCircle and ShapRectangle
and from the exe i use LoadLibrary and GetProcAddress .
typedef CMyIShape* (*CREATE_OBJECT) ();
CMyIShape*xCls ;
//===================== from ShapeCircle.Dll
pReg= (CREATE_OBJECT)GetProcAddress (hInst ,"CreateShape");
xCls = pReg();
now xCls give all access of base class. but how to get pointer of funciton Fn_GetRadious() or how to get access.
thanks in advance.could you please tell me in detail. why so. or any reference for it. i love to read.
i don't know this is bad way.. but how? i would like to know.
I indicated in the second sentence. Classes can be implemented differently by different compilers. For example, the alignment of member variables may differ. Also there is the pitfall that a class may be allocated within the DLL but deallocated in the client
code. But the allocation/deallocation algorithms may differ across different compilers, and certainly between DEBUG and RELEASE mode. This means that you must ensure that if the DLL is compiled in Visual Studio 2010 / Debug mode, that the client code is also
compiled in Visual Studio 2010 / Debug mode. Otherwise your program will be subject to mysterious crashes.
is there any other way to archive same goal?
Of course. DLL functionality should be exposed as a set of functions that accept and return POD data types. "POD" means "plain-ole-data" such as long, wchar_t*, bool, etc. Don't pass pointers to classes.
Obviously classes can be implemented within the DLL but they should be kept completely contained within the DLL. You might, for example, expose a function to allocate a class internally to the DLL and another function that can be called by the client code
to free the class. And of course you can define other functions that can be used by the client code to indirectly call the class's methods.
and why i need to give header file of ShapCircle and shapRectangle class, even i am not using in exe too. i though it is enough to give only MyIShape.h so with this any one can make new object.
Indeed you don't have to, if you only want to call the public properties and methods that are defined within MyIShape.h. -
Set fields of derived class in base class constructor via reflection?
Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
Many thanks for your feedback!
Norman
public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
abstract static class A {
A() {
try {
getClass().getDeclaredField("x").setInt(this, 42);
} catch (Exception e) {
throw new RuntimeException(e);
static class B extends A {
int x;
B() {
B(int x) {
this.x = x;
public void testThatItWorks() {
assertEquals(42, new B().x);
assertEquals(99, new B(99).x);
}why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
Framework:
public abstract class Operator {
public abstract void initialize();
}Plug-In:
public class SomeOperator extends Operator {
@Parameter(defaultValue="42", interval="[0,100)")
double threshold;
@Parameter(defaultValue="C", valueSet="A,B,C")
String mode;
public void setThreshold(double threshold) {this.threshold = threshold;}
public void setMode(String mode) {this.mode = mode;}
// called by the framework after default values have been set
public void initialize() {
}On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance. -
Hi pls go through the below code, can any one give me solution how to access the Derived class method in this Point.
Note: In the below code , only in runtime we will come to know which Derived class method is going to invoke(So in runtime we will get Derived class name in the form of String). So Iam trying to Use Class.forName("Clas name") to create the instance of the Derived class and then type casting to base class.
Why iam casting to base class is , since only in the run time we are geting the Derived class name.
Result : iam geting the compiletime error says that no valid method fond in Mybase though it contains the reference of derived.
abstract class MyBase
public void display(int i)
System.out.println(" Base class Method");
class MyDerived extends MyBase
public void display(String str)
System.out.println("Derived class Mthode");
class MyMain
public static void main(String arg[])
String DrivObj=arg[0];
MyBase baseObj=(MyBase) Class.forName("DrivObj").newInstance();
baseObj.display("SomeString"); }
}The problem is, can not have subclass reference bcoz
iam geting the subclass name only in the runtime and
one more thing is cant touch my base and subclass to
do changes as u said Your design is then definately very bad.
, is there any other way to do
it.Yes, you can use reflection to invoke the method.
Kaj -
Force Derived Class to Implement Static Method C#
So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So
I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.
Also, the signature of these CRUD methods are similar.
E.g. ClassA will have CRUD methods with these type of Signatures
public static List<ClassA> Get()
public static ClassA Get(int ID)
public static bool Insert(ClassA objA)
public static bool Update(int ID)
public static bool Delete(int ID)
ClassB will have CRUD signatures like
public static List<ClassB> Get()
public static ClassB Get(int ID)
public static bool Insert(ClassB objB)
public static bool Update(int ID)
public static bool Delete(int ID)
So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.
For E.g. BaseClass will have CRUD methods like
public virtual static List<BaseClass> Get()
public virtual static BaseClassGet(int ID)
public virtual static bool Insert(BaseClass objBase)
public virtual static bool Update(int ID)
public virtual static bool Delete(int ID)
But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.
So is there any way out?
Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.
Anything that can be done with Abstract class?Hi,
With static methods, this is absolutely useless.
Instead, you could use the "Singleton" pattern which restrict a class to have only one instance at a time.
To implement a class which has the singleton pattern principle, you make a sealed class with a private constructor, and the main instance which is to be accessed is a readonly static member.
For example :
sealed class Singleton
//Some methods
void Method1() { }
int Method2() { return 5; }
//The private constructor
private Singleton() { }
//And, most importantly, the only instance to be accessed
private static readonly _instance = new Singleton();
//The corresponding property for public access
public static Instance { get { return _instance; } }
And then you can access it this way :
Singleton.Instance.Method1();
Now, to have a "mold" for this, you could make an interface with the methods you want, and then implement it in a singleton class :
interface ICRUD<BaseClass>
List<BaseClass> GetList();
BaseClass Get(int ID);
bool Insert(BaseClass objB);
bool Update(int ID);
bool Delete(int ID);
And then an example of singleton class :
sealed class CRUDClassA : ICRUD<ClassA>
public List<ClassA> GetList()
//Make your own impl.
throw new NotImplementedException();
public ClassA Get(int ID)
//Make your own impl.
throw new NotImplementedException();
public bool Insert(ClassA objA)
//Make your own impl.
throw new NotImplementedException();
public bool Update(int ID)
//Make your own impl.
throw new NotImplementedException();
public bool Delete(int ID)
//Make your own impl.
throw new NotImplementedException();
private CRUDClassA() { }
private static readonly _instance = new CRUDClassA();
public static Instance { get { return _instance; } }
That should solve your problem, I think...
Philippe -
Casting base class object to derived class object
interface myinterface
void fun1();
class Base implements myinterface
public void fun1()
class Derived extends Base
public class File1
public myinterface fun()
return (myinterface) new Base();
public static void main(String args[])
File1 obj = new File1();
Derived dobj = (Derived)obj.fun();
Giving the exception ClassCastException......
Can't we convert from base class object to derived class.
Can any one help me please...
Thnaks in Advance
Bharath kumar.When posting code, please use tags
The object returned by File1.fun() is of type Base. You cannot cast an object to something it isn't - in this case, Base isn't Dervied. If you added some member variables to Derived, and the compiler allowed your cast from Base to Derived to succeed, where would these member variables come from?
Also, you don't need the cast to myinterface in File1.fun()
Also, normal Java coding conventions recommend naming classes and interfaces (in this case, myinterface) with leading capital letters, and camel-case caps throughout (e.g. MyInterface) -
Derived class also implements interface?
Hi guys,
If a base class A implements an interface (e.g. Comparable), does a derived class of A also implement this interface (or is of this type e.g Comparable, if this is a more correct way to say it)??
If so, would it be wrong to write "public class B extends A implements Comparable", because class A already implements it?
I am aware of that class B will inherit methods from class B and that way have "compareTo()" method. But can objects of class B be plugged in for method parameter of Comparable ( someMethod(Comparable obj) )?LencoTB wrote:
Hi guys,
If a base class A implements an interface (e.g. Comparable), does a derived class of A also implement this interface (or is of this type e.g Comparable, if this is a more correct way to say it)??Yes. The way you said it is fine, although another way to say it is "Comparable is a base interface(or class) of derived class B"
>
>
If so, would it be wrong to write "public class B extends A implements Comparable", because class A already implements it?Not necessarily, but it is unnecessary. The only reason you would do this is to specifically document that the class is changing the implementation of compareTo.
>
I am aware of that class B will inherit methods from class B and that way have "compareTo()" method. But can objects of class B be plugged in for method parameter of Comparable ( someMethod(Comparable obj) )?use "implements Comparable<B>" -
Managing constants in base / derived classes
Hi there,
The problem:
I'm facing what is certainly a simple problem but fail to come up with an acceptable solution. What I'd like to do is managing constants in a base class and derived class... which for some reasons are not parts of the same package. Also, these constants may have different values in the derived base.
Down to earth description:
Class base uses a set of constants A=1, B=2, C=3.
Class derived should be provided with similarly named constants but they may have different values A=10, B=20, C=30. I could declared these constants in the classes themselves but somehow I think this is ugly.
A "solution" that does not work:
Assume for a moment that I'm just a very naive programmer (which actually I am... but anyway...). I would them come up with something like:
package base;
import base.Constants;
public class Base {
public Base() {
public void myfunction() {
System.out.println("My constant: " + Constants.A);
}and
package derived;
import derived.Constants;
public class Derived extends Base {
public Derived() {
}Now of course this is stupid since Derived.myfunction() prints the value of the constants given by Base.myfunction()The question is: is there a static construction that would allow me to have the desired behaviour? What I mean is that I don't want to provide a "Constants" object nor an hashtable dynamically loaded or whatever.
Bonus question:
I'm not a pro in OOP (seriously guys... C rocks! Oops, wrong forum :-) but it seems to be a case of "code inheritance" vs "behaviour inheritance" (I just made those expressions up!). What I mean is: if what is inherited is the actual "code" of the methods (as if a huge copy paste took place) then the naive solution would work. But in the real world, a "behaviour inheritance" is at work in the sense that what is inherited is the "behaviour" (or, more bluntly, simply the code as compiled in the base class). Hmm... Am I making any sense here? Is that distinction theorized in some way? I tried to search a bit by myself but did not know where to start.
Thanks,I mucked around with this exact problem a while back.
The (simplified) scenario is AbstractCourse is extended by CookingCourse, WritingCourse, and BusinessCourse. Every course has a basePrice and a materialsCost... both of which vary from course to course... The same price calculation applies to all types of course, just the amounts will vary.
totalPrice = basePrice + materialsCost The traditional non-oo solution is simple enough... you would just create a "table" of all six contstants, and a function with a switch statement...
but How to do this "The OO Way"?
What I came up with is:
class BaseCourse {
abstract double getBasePrice();
abstract double getMaterialsCost();
public double getPrice() {
return getBasePrice() + getMaterialsCost();
public class CookingCourse {
private static final double BASE_PRICE = 300.00;
private static final double MATERIALS_COST = 112.60;
public double getBasePrice() { return CookingCourse.BASE_PRICE }
public double getMaterialsCost() { return CookingCourse.MATERIALS_COST }
public class WritingCourse {
private static final double BASE_PRICE = 200.00;
private static final double MATERIALS_COST = 50.00;
public double getBasePrice() { return WritingCourse.BASE_PRICE }
public double getMaterialsCost() { return WritingCourse.MATERIALS_COST }
public class BusinessCourse {
private static final double BASE_PRICE = 600.00;
private static final double MATERIALS_COST = 18.12;
public double getBasePrice() { return BusinessCourse.BASE_PRICE }
public double getMaterialsCost() { return BusinessCourse.MATERIALS_COST }
}The base class specifies that each subclass must be able to tell it's base price, and it's materials cost... then we implement the calculation on those values just once, in the base class.
For all I know there are much more succinct, flexible, efficient, and basically much more smarter ways of doing this... this is just a way that worked for me... and it's simple enough so even I can follow it.
Java can be a very very very very verbose language :-( ... But hey it still shits on C ;-)
Cheers. Keith.
Edited by: corlettk on 23/05/2008 11:17 - typos -
Error when defining a variable from a class
Hi,
I'm getting this error message when trying to define a
variable from a class:
'1086: Syntax error: expecting semicolon before left paren.'
I can't see where the error is.
The scripts Question.as and Codeframe.as is located int the
folder Mycomponents under the project.
Regards
/Acke
**** Main app *****
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.CloseEvent;
import myComponents.*;
var Question():myComponents.Question=new Question(); // !!
This line causes the error !!
other code goes here....
]]>
</mx:Script>
**** The class definition ******
package myComponents
//import other classes needed
import Mycomponents.Codeframe
public class Question {
// Define properties and methods.
// Define public vars.
public var Qtype:string;
public var Condition:string;
public var Qnumber:string;
public var Qheading:string;
public var Pretext:string;
public var Qtext:string;
public var Posttext:string;
public var Codeframe():string;
public var Reserved:string;
public var EditableFrom:string;
public var EditableTo:string;
public var Decimal:string;
public var SetQfactor:string;
public var Logic_if():string;
public var Logic_then():string;
// Public constructor.
//public function Question(){
// do stuff to set initial values for properties
public function Question(Type:string,
Condition:string,
Qnumber:string,
Qheading:string,
Pretext:string,
Qtext:string,
Posttext:string,
Codeframe():string,
Reserved:string,
EditableFrom:string,
EditableTo:string,
Decimal:string,
SetQfactor:string,
Logic_if():string,
Logic_then():string,
):Void
this.Type=Type;
this.Condition=Condition;
this.Qnumber=Qnumber;
this.Qheading=Qheading;
this.Pretext=Pretext;
this.Qtext=Qtext;
this.Posttext=Posttext;
this.Codeframe()=Codeframe();
this.Reserved=Reserved;
this.EditableFrom=EditableFrom;
this.EditableTo=EditableTo;
this.Decimal=Decimal;
this.SetQfactor=SetQfactor;
this.Logic_if()=Logic_if();
this.Logic_then()=Logic_then();
}1.
It should be
var theQuestion:Question = new
Question(sType,sCondition:string,sQnumber,sQheading,sPretext,sQtext,sPosttext,
sCodeframe,sReserved,sEditableFrom,sEditableTo,sDecimal,sSetQfactor,sLogic_if,sLogic_then )
As you don't have default values in the constructor - you
should specify the parameters.
2. why do use type "string" ? It should be "String" if you
refer to a standard type
3. What are you trying to say by this:
public var Codeframe():string;
public var Logic_if():string;
public var Logic_then():string;
There should not be any parenthesis in the variable
declaration.
4.
this is wrong
var Question():Question=new Question();
this even wronger
var Question():Array=new Question(); // I'm trying to create
an array here anyway...could this be the problem??
no parenthesis!
var Qs():Question=new Question();
hmmmm....
.var Qs()=new Question();
I think you should start reading from the following link to
get more understanding of the variables, types & declarations:
http://livedocs.adobe.com/flex/2/docs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDo cs_Parts&file=00001863.html
Cheers,
Dmitri.
Maybe you are looking for
-
How can I recover an earlier version of an Apple Notes document
Hello, I must have deleted an earlier version of an Apple Notes document. My Mac is running OS X version 10.9.2. Apple Notes runs on my Macbook Pro and my Iphone 4S, and I've seen my Apple Notes documents on Icloud. However, the particular doucment
-
OS 10.5.7 and problems with downloads
It seems there are a lot of bugs with this new update. Mine in particular is that I can't seem to download apps from the internet. Tried Apple support and after a day on the phone I have no resolution. A second laptop in the house has no problems and
-
The duplication of a Company Contact for a different person at the same Company should be possible ... I'd think - which the BB Tour's Help function does not address (only minor changes to an existing Company Contact individual would be required to c
-
i cant see any of my photos unless i click on them same goes with downloads all i see is the document looking icon that says jpeg , i can see the pics in my i photo but not in my folders ? i think i threw a folder away out of application supp0rt ? r
-
Canon 30i footage not being read by sony HVR V1U
Hello out there, So I have a whack of tapes to import, shot using the Canon XLH1- I'm not sure if they were recorded at 30F or 60i However, I can't seem to find the correct 'tape format' on the HVR V1U to play them back. Anyone run into this problem?