New object w/o constructor ?
Hi,
Can we instantciate a new instance without calling the class Constructor? Is there such a thing ? thx
P
Ultimately, somebody's got to call a constructor to make a new object, whether straight or by reflection. There might be a method such as clone() or getInstance() that you can call so that you yourself don't have to call a constructor, but eventually one is called. Does that answer your question? Are you just curious, or is there some reason you don't want to call a constructor?
Similar Messages
-
What is the diffrence between extends and creating new object?
HI ALL,
what is the diffrence between extends and creating new object?
meaning
class base{
class derived extends base{
class base{
class derived {
derived(){
base var = new base();
can u people tell me diffence from the above examples.
THANKS.
ANANDAWhen you create a new object you have to supply the class to which that
object belongs. A class can extend from another class. If it does so
explicitly you can define the 'parent' class from which the class extends.
If you don't explicitly mention anything, the class will implicitly extend
from the absolute base class named 'Object'.
Your example is a bit convoluted: when you create a Derived object,
its constructor creates another object, i.e. an object from the class from
which the Derived class extends.
Extending from a class and creating an object don't have much in common.
kind regards,
Jos -
New-object itextsharp causes an error
Hi, i am trying to use powershell to read a pdf document with the following code
[System.Reflection.Assembly]::LoadFrom(".\itextsharp.dll")
$reader = New-Object iTextSharp.text.pdf.PdfReader -ArgumentList ".\201408_issue.pdf"
for ($page = 1; $page -le $reader.NumberOfPages; $page++) {
$lines = [char[]]$reader.GetPageContent($page) -join "" -split "`n"
foreach ($line in $lines) {
if ($line -match 'test')
$matches[1]
I get an error though, has anyone encoutnered this? Thanks
New-Object : Exception calling ".ctor" with "1" argument(s): "Object reference not set to an instance
of an object."
At C:\PsScripts\test\PDFReader\PDFReader.ps1:2 char:11
+ $reader = New-Object iTextSharp.text.pdf.PdfReader -ArgumentList ".\201408_RIN_i ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObject
CommandPS C:\PsScripts\test\PDFReader> $error[0].Exception | Format-List * -Force
ErrorRecord : Exception calling ".ctor" with "1" argument(s): "Object reference not
set to an instance of an object."
StackTrace : at System.Management.Automation.DotNetAdapter.AuxiliaryConstructorInvo
ke(MethodInformation methodInformation, Object[] arguments, Object[]
originalArguments)
at
System.Management.Automation.DotNetAdapter.ConstructorInvokeDotNet(Type
type, ConstructorInfo[] constructors, Object[] arguments)
at
Microsoft.PowerShell.Commands.NewObjectCommand.CallConstructor(Type
type, ConstructorInfo[] constructors, Object[] args)
WasThrownFromThrowStatement : False
Message : Exception calling ".ctor" with "1" argument(s): "Object reference not
set to an instance of an object."
Data : {}
InnerException : System.NullReferenceException: Object reference not set to an instance
of an object.
at iTextSharp.text.pdf.PdfReader.ReadObjStm(PRStream stream,
IntHashtable map)
at iTextSharp.text.pdf.PdfReader.ReadDocObj()
at iTextSharp.text.pdf.PdfReader.ReadPdf()
TargetSite : System.Object AuxiliaryConstructorInvoke(System.Management.Automation.Met
hodInformation, System.Object[], System.Object[])
HelpLink :
Source : System.Management.Automation
HResult : -2146233087
Any meaning to you? -
hi, i'm wondering if i could have everything all set up(canvas3d,simpleuniverse,etc.) and i wanted to add to add a transformgroup to the BranchGroup, would everything update to show the new transformgroup?
adn is a simepleuniverse like a virtualuniverse?i see on Canvas3d there's an update() meathod, do i use that?No, please don`t.
The scengraph will update if you set the capability
BranchGroup.ALLOW_CHILDREN_EXTEND
before you add a new object
You should update a scengraph from a Behavior. Please see
You should read the javadoc for Behavior
When the Java 3D behavior scheduler invokes a Behavior object's processStimulus method, that method may perform any computation it wishes. Usually, it will change its internal state and specify its new wakeup conditions. Most probably, it will manipulate scene graph elements. However, the behavior code can only change those aspects of a scene graph element permitted by the capabilities associated with that scene graph element. A scene graph's capabilities restrict behavioral manipulation to those manipulations explicitly allowed.
The application must provide the Behavior object with references to those scene graph elements that the Behavior object will manipulate. The application provides those references as arguments to the behavior's constructor when it creates the Behavior object. Alternatively, the Behavior object itself can obtain access to the relevant scene graph elements either when Java 3D invokes its initialize method or each time Java 3D invokes its processStimulus method.
Behavior methods have a very rigid structure. Java 3D assumes that they always run to completion (if needed, they can spawn threads). Each method's basic structure consists of the following:
* Code to decode and extract references from the WakeupCondition enumeration that caused the object's awakening.
* Code to perform the manipulations associated with the WakeupCondition
* Code to establish this behavior's new WakeupCondition
* A path to Exit (so that execution returns to the Java 3D behavior scheduler)
regards -
Why do we allocate space for a new object???
When we create a new object, we instantiate it. Why do we do this. I read that we are allocating space for it. What is allocating space and why is it necessary??
Okay, say you have an object called Stick, which descibes a physical stick's characteristics:
class Stick
private int length;
Stick()
//unparameterized constructor
length = 1;
Stick(int l)
//parameterized constructor
length = l;
public int getLength()
return length;
Pretty basic, right? Okay, looking at this code, you might say "well this is a class, not an object because it describes something, it's not an actual instance of the class". Right. So what people do is they instantiate things like Stick() into a static class (such as main) like so:
class Thingy
public static void main(String args[])
Stick s1 = new Stick(); //calls the unparameterized constructor
Stick s2 = new Stick(4); //calls the parameterized constructor
System.out.println("Stick 1's length is "+s1.getLength());
System.out.println("Stick 2's length is "+s2.getLength());
The unparameterized constructor line creates an instance (which is the same thing as an object) of class Stick using no parameters. The parameterized does the same, only it uses a length of 4 instead of the default 1 that the other constructor uses. The two instances s1 and s2 use the same class template, and can call the same methods, such as getLength(), but they contain different information in their data fields, for example "length" in class Stick. And that's how constructors work, and why they're useful. They're all about deriving a useful instance from either limited or abundant information. -
I want to test the input parameters to a constructor and determine if an invalid parameter has been supplied.
If I use:
Thingy myThingy = new Thingy("invalid value");
is it up to the programmer of the above to catch the error, either through exception handling or some other form of error checking, and perform
myThingy = null;
to render the partially initialized object ready for garbage collection?
Is there a way in the constructor itself to indicate that the object shouldn't be created and null should be returned as the result of the "new" operation?
Thanks,
JohnBut I'd say Clem1986 still has a point. Even in the constructor
Foo() throws Exception {
throw new Exception("Bollocks");
}there's the implicit call to super() and instance initializers before you arrive at throw. From JVM spec: The new instruction does not completely create a new instance; instance creation is not completed until an instance initialization method has been invoked on the uninitialized instance. Which is done above. Whether this qualifies in OP's context as completing instance creation or instantiating an object I don't know. But you could work with it in the constructor, and once you get to throw, memory has been allocated, all superclasses have been initialized (which might involve heavy allocation/computation), default values were assigned to fields and instance initializers have executed. Only now can you decide to "abort new object creation" by completing abruptly and not "returning" the reference to the newly-(partially-)created object to the caller. -
Difference between "clone" and creating a new object
Hi experts,
What on earth is the difference between:
1)creating a new object by using the "clone()" method and
2) just creating a new object?
Let me be a bit more specific:
if there's a class called "Book" and suppose we've already created an object called "japaneseBook", any difference between "Book spanishBook = new Book();" and "Book spanishbook = japaneseBook.clone()"?
Thank you.
EileenThe purpose is very obvious. At anytime in the running application, when Objects have been changed, and you desire to make another one of the same kind, you can't use new. You would use clone. The newer Object would have the same values in the variables. Now i got a question.. an important issue.
public class XYZ{
public static int t = 10;
} // default constructor is present by default.
//In another portion i have the following..
private XYZ x = new XYZ( ); // private Object!!
// Now what about this one????
public XYZ x1 = x.clone( ); // public !!, well
What impact of this code can be there to break the rules of good OOP design??? Is it that a clone Object would have the same access of itself (not of its variables) or different one????????? -
Reusing a variable from a new object instance
I'm developing a stock list array for an assignment I'm currently working on. I've got most of it done, and it seems to be working for the most part, but I'm having trouble getting an array to accept individual variable entries created by new object instances in TestQ3.java.
I think problem is because the variable itemCode in CraftItem.java is being overwritten by the creation of a new object instance in the TestQ3.java file. I've tested it and believe this to be true.
I can add a String of my own choosing by using testArray.addCraftItemToStock(itemCode); line but I want to get the program to reuse the itemCode values that have already been created by the four new object instances in TestQ3.java. For example, I want to be able to add more instances of them to the testArray.
As I'm still relatively new to Java programming, I'm wondering how to do this. I've tried several solutions but I'm not getting anywhere. I'd appreciate it if anyone has any ideas?
Here's my code:
TestQ3.java
public class TestQ3 {
public static void main(String args[]) {
// creating a new StockItem array
CraftStock testArray = new CraftStock(CraftStock.initialStockCapacity);
// creating new object instance for Glue
Glue gluePVA = new Glue("PVA Glue",250,"789012",2.50);
// adds gluePVA item code to the testArray list
// testArray.addCraftItemToStock(gluePVA.getItemCode());
// creating new object instance for Card
Card colouredCard = new Card ("Coloured Card","A3","654321",1.25);
// adds coloured card item code to the testArray list
// testArray.addCraftItemToStock(colouredCard.getItemCode());
// creating new object instance for Glue
Glue superGlue = new Glue ("Super Glue",25,"210987",1.50);
// adds superGlue item code to the testArray list
// testArray.addCraftItemToStock(superGlue.getItemCode());
// creating new object instance for Card
Card whiteCard = new Card ("White Card","A4","123456",0.50);
// adds superGlue item code to the testArray list
// testArray.addCraftItemToStock(whiteCard.getItemCode());
// display complete stocklist
testArray.displayCraftStockList();
// this adds the itemCode from gluePVA to the array but
// it comes out as the last itemCode entry 123456 rather than 789012
// when I run the code. The problem may lie with variable itemCode
testArray.addCraftItemToStock(gluePVA.getItemCode());
// display complete stocklist
testArray.displayCraftStockList();
CraftItem.java
public class CraftItem {
// instance variables
public static String itemCode;
private double price;
//private int stockCount;
// constructor
public CraftItem(String itemCodeValue, double itemPriceValue){
itemCode = itemCodeValue;
price = itemPriceValue;
//CraftStock.addCraftItemToStock(itemCode);
//stockCount++;
// getter for itemCode
public String getItemCode() {
return itemCode;
// getter for price
public double getPrice() {
return price;
// setter for itemCode
public void setItemCode(String itemCodeValue) {
itemCode = itemCodeValue;
// setter for price
public void setPrice(double itemPriceValue) {
price = itemPriceValue;
// toString() value
public String toString() {
return "Item code is " + itemCode + " and costs " + price + " pounds.";
Glue.java
public class Glue extends CraftItem{
// Instance variables
private String glueType;
private double glueVolume;
// Constructor
public Glue(String glueType, double glueVolume,
String itemCodeValue, double itemPriceValue) {
super(itemCodeValue, itemPriceValue);
glueType = glueType;
glueVolume = glueVolume;
// getter
public String getGlueType() {
return glueType;
// getter
public double getGlueVolume() {
return glueVolume;
// setter
public void setGlueType(String glueTypeValue) {
glueType = glueTypeValue;
public void setGlueVolume(double glueVolumeValue) {
glueVolume = glueVolumeValue;
// toString
public String toString() {
return glueType + ", " + glueVolume + "ml, item code is "
+ super.getItemCode() + " and costs " + super.getPrice() + " pounds.";
Card.java
public class Card extends CraftItem{
// instance variables
private String cardType;
private String cardSize;
// Constructor
// added super(itemCodeValue, itemPriceValue) to call on CraftItem
public Card(String cardTypeValue, String cardSizeValue,
String itemCodeValue, double itemPriceValue) {
super(itemCodeValue, itemPriceValue);
cardType = cardTypeValue;
cardSize = cardSizeValue;
// getter
public String getCardType() {
return cardType;
// getter
public String getCardSize() {
return cardSize;
// setter
public void setCardType(String cardTypeValue) {
cardType = cardTypeValue;
// setter
public void setCardSize(String cardSizeValue) {
cardSize = cardSizeValue;
// toString
// using super. to call on methods from superclass CraftItem
public String toString() {
return cardType + ", size " + cardSize + ", item code is "
+ super.getItemCode() + " and costs " + super.getPrice() + " pounds.";
CraftStock.java
public class CraftStock {
public static int currentStockLevel;
public static String[] craftStock;
public static int initialStockCapacity = 10;
public CraftStock(int initialStockCapacity) {
currentStockLevel = 0;
craftStock = new String[initialStockCapacity];
public int currentStockLevel() {
return currentStockLevel;
public static void addCraftItemToStock(String itemCodeValue) {
if(currentStockLevel == 10){
System.out.println("Stock list full: cannot add new item code." +
"\nPlease remove an item if you want to add a new one.");
else{
craftStock[currentStockLevel] = itemCodeValue;
currentStockLevel++;
System.out.println("Item added");
public void removeCraftItemFromStock(String itemCode){
findStockItem(itemCode);
int i = -1;
do {
i++;
} while (!craftStock.equals(itemCode));
for (int j = i; j < currentStockLevel - 1; j++) {
craftStock[j] = craftStock[j + 1];
currentStockLevel--;
System.out.println("Item removed");
private int findStockItem(String itemCode){
int index = 0;
for(int i = 0; i < currentStockLevel; i++){
if(craftStock[i].equals(itemCode)){
index = i;
break;
else{
index = -1;
return index;
public void displayCraftStockList() {
if(currentStockLevel == 0){
System.out.println("There are no items in the stock list");
else{
for(int i = 0; i < currentStockLevel; i++){
System.out.println("Item at " + (i + 1) + " is " + craftStock[i]);
Message was edited by:
NikariusAn instance variable relates to an object. If you require a variable to be available across multiple objects of the same class then I suggest you declare a class variable using the static keyword in your declaration.
HTH -
How new objects are instantiated when reading from object stream?
Hi,
How the serializable API instantiates new objects when reading from stream?
First it needs to create a new instance of a class and then fill its' fields with a serialized data. But not all serializable classes have empty constructor (as it have java beans) to make simple call of Class.newInstance(). Is there any way to create a virgin instance of any class?
Ant�nI found the way, but it is not a solution:
Constructor serializableConstructor = sun.reflect.ReflectionFactory.getReflectionFactory().newConstructorForSerialization( Class instanceClass, Constructor superClassEmptyConstructor );
Object obj = serializableConstructor.newInstance();This "magic" method creates an empty constructor for a serializable class from empty constructor of any superclass. The limitation is that a first non-serializable superclass must have an empty constructor.
As this magic method locates in a package sun.** I think this will not work with other JREs. -
What happens to objects when you redeclare a new object?
... and is there a more proper way of "deleting" them from memory, or is it a case of waiting until the garbage collector in java sweeps them up?
i.e.
private CustomObjectType myObject;
public final void myMethod() {
myObject = new CustomObjectType("I am the first object");
// do some temporary work with myObject
/// now I need to do more work with another temporary object, so just replace the "link"
myObject = new CustomObjectType("I am a second object");
Is it better to declare new variables to hold this second object?
Should a person declare the object to be null when no longer required?
Do I ever need to worry about this, does the garbage collector sort out references for me?
(Please go easy, still learning and don't really need to know this right now but I'm curious! :)What happens to objects when you redeclare a new object?If you go:
Dog myDog = new Dog();
and then go:
Dog myDog = new Dog();
you are replacing the first reference to Dog() with another one. I don't think it would make sense to do this because it is redundant.
But if you go:
static Dog myDog = new Dog();
and then go:
static Dog myDog = new Dog();
then then second one will be ignored because the first one already assigned Dog() to myDog.. so the second one won't replace the first one - it will just be ignored or generate an error.
is there a more proper way of "deleting" them from memory, or is it a case of waiting until the garbage collector in java sweeps them up?In c and c++ you have to think about when the life of an object ends and destroy the object to prevent a memory leak. But in Java the garbage collector takes this task on if a certain amount of memory is used. If you don't use a lot of memory the gc won't bother and the objects will be destroyed when you exit the program.
You can use:
finalize(){
// insert code to be executed before the gc cleans up
and if you call System.gc() (which you probably won't need to do) then the code in the finalize() method will run first e.g. to erase a picture from the screen before collecting the object.
private CustomObjectType myObject;public final void myMethod() {
myObject = new CustomObjectType("I am the first object");
// do some temporary work with myObject
/// now I need to do more work with another temporary object, so just replace the "link"
myObject = new CustomObjectType("I am a second object");
you could do:
public class CustomObjectType{
//this constructs an instance of the class using a string of your choice
CustomObjectType(String str) {
System.out.println(str);
static void main(String[] args){
CustomObjectType myObject = new CustomObjectType("I am the first object");// This sends the constructor the string you want it to print
CustomObjectType myObject2 = new CustomObjectType("I am the second object");// This sends the constructor the string you want it to print
}Bruce eckel wrote Thinking in Java 4th edition considered to be the best book on Java because of how much depth he goes into, although some recommend you should have atleast basic programming knowledge and a committment to learn to get through the book.
I just started it and it helps a lot. Maybe u could borrow it from the library.. good luck! -
Doubt in creation of a new object
Hi All,
I have one doubt in creation of a new object.If a new object is to be created and it is not a subtype
of any existing object, then what should we enter in the Program field for creating the object?
I hope I am clear with my question.
Thanks in Advance,
Saket.Hi Saket,
Following will be required for created a custom business object.
1. Object Type - ZTEST (Internal Techincal Key)
2. Object Name - ZTESTNAME (Technical Key Name)
3. Name - TEST (Name of BO, it is used while selecting the object type)
4. Description - (Short Description of BO)
5. Program - ZTESTPROGRAM (ABAP program in which the methods of the object type are implemented)
6. Application - A or B.. etc (Area to which your BO is related)
Please remember that you can learn these basic things by giving F1 help on those fields and in HELP.SAP.COM.
Regards,
Gautham Paspala -
Creating a new object at runtime
What I want to do is dynamically change the name of a object
everytime I create a new one, what I mean excatly is like make it
so that I can some how increment a value of a variable and apply it
to an object anme... so I get something like this
objectName0, objectName1, objectName2, objectName3 and so on.
I basically want to make it so that I always have a new object to
use... how would I go about doing this?You don't need exec, the api provides this functionality for you. Look at the java.util.jar package.
-
It will not parse! Creating a new object in the universe
Hi, we have a universe and BO reports. They work fine for our clients. We are on BO XI r3.1. Now, one client captures an additional piece of info. They would like to report against this and add it high up on our drilling heirarchy. "Sure, no problem". For the following I was logged in as administrator.
The additional data field is a 3 character code.
1) We added an additional column to the actual database table.
2) In Universe Designer, I refreshed universe structure and could see the additional column
3) Created an object 'Acode' that refers to db.new_field
4) Exported universe
Maybe worth mentioning that I can see this object and use it in reports fine in Infoview.
Now, I need to create a new object that will be one of 2 strings based on the 3 character code (Acode) i.e. the 'Atype' can be X or Y.
Here's my code and it just will not parse:
CASE
WHEN @Select(AFolder\Acode) = 'CEL'
THEN 'X'
ELSE u2018Yu2019
END
Error I get is:
Parse failed:Eception:DBD ODBC SQL Server driverStatement could not be prepared.State 42000
I'd appreciate any help, believe me I have searched the forums!
Thanks, EddieLook at following SAP NOtes.
1373739
1184304
Regards,
Bashir Awan -
Setting the name of a new object from a string
Is there anyway I can set the object name of a newly created
object from a string?
eg.
(the code below generates a compile time error on the
variable declaration)
public function addText(newTxt:String, txt:String,
format:TextFormat):void {
var
this[newTxt]:TextField = new TextField();
this[newTxt].autoSize = TextFieldAutoSize.LEFT;
this[newTxt].background = true;
this[newTxt].border = true;
this[newTxt].defaultTextFormat = format;
this[newTxt].text = txt;
addChild(this[newTxt]);
called using>
addText("mytxt", "test text", format);
I could then reference the object later on without using
array notation using mytxt.border = false; for example
There are many a time when I want to set the name of a new
object from a string.
In this example I have a function that adds a new text object
to a sprite.
The problem is, if I call the function more than once then
two textfield objects will exist, both with the same name. (either
that or the old one will be overwritten).
I need a way of setting the name of the textfield object from
a string.
using
var this[newTxt]:TextField = new TextField()
does not work, If I take the "var" keyword away it thinks it
a property of the class not an object.
resulting in >
ReferenceError: Error #1056: Cannot create property newTxt on
Box.
There must be a way somehow to declare a variable that has
the name that it will take represented in a string.
Any help would be most welcome
ThanksUsing:
var this[newTxt]:TextField = new TextField()
is the right approach.
You can either incrment an instance variable so that the name
is unique:
newTxt = "MyName" + _globalCounter;
var this[newTxt]:TextField = new TextField();
globalCounter ++;
Or store the references in an array:
_globalArray.push(new TextField());
Tracy -
Getting ORA-20001: Creation of new object is not allowed: !!
Hi Am getting ORA-20001: Creation of new object is not allowed while enabling constraints after importing the dumps from source to target datbase,can anyone assist me to fix this issue.
Hi Osama/Mustafa,Thanks for your quick response,can you please explain me the following things-
1)As i don't have privilege to run the DBA_XX views,am not able to run those queries-
SELECT OWNER, TRIGGER_NAME, TRIGGER_BODY FROM DBA_TRIGGERS WHERE TRIGGER_TYPE IN ('AFTER EVENT', 'BEFORE EVETN') AND TRIGGERING_EVENT LIKE '%CREATE%';
can you tell me what output it'll throw,based on this output how will we fix the issue.
2)SELECT * FROM dba_sys_privs WHERE privilege = 'UNLIMITED TABLESPACE';
why we need to check this privilege?as i don't have privilege to run this one in my db.
3)select * from dba_source where upper(text) like upper('%Creation of new object is not allowed%');
as i don't have privilege to run this one in my db,already i got the object name from my logfile
and more you have quoted"This is an error of someone that coded purposely on your database, probably dba or a developer who has privilege and again it is in a database event trigger"
4)can you explain me much more deeper about the root cause and as already sent note to my DBA,can you explain me the solution to fix this issue ?
Maybe you are looking for
-
Levels don't always work?
I get pdfs of drawings/scans from clients and most of the time when I open them in photoshop and use levels to darken them it works. But sometimes I'll get a pdf where it will darken in the levels preview but when I click ok it goes back to the way i
-
Bonded Warehouse: Cannot create Customs Declaration
Does anyone have any experience with Bonded Warehouse that they could help with the following? I have setup Bonded Warehouse in GTS, but am unable to create any Customs Declarations from the PO/Goods Receipt. After creating the PO, Delivery, and Good
-
Want to use Oracle in SavingsAccount example
Hi I am able to run the SavingsAccount sample aaplication using the Cloudscape db provided with J2EE. I want to run the same application with Oracle 8i.I have already run the savingsaccount.sql on Oracle to create the table. Please help me. I want to
-
CProjects 4.5 Custom fields as Dropdowns
Can anyone describe how a custom field can be made to appear as a dropdown in cprojects. I am able to enhance the customer includes to create them as Text fields but need to know how can they be created as dropdown list. Thanks and regards Vishal
-
HT5312 What if my rescue mail address is not valid anymore and I forgot security questions?
I felt a need to change my password for iCloud usage (After over a year and after getting new iPhone). Unfortunately, I truly forgot my security questions (I do not remember setting them up ) and what makes the story even worse: I do not use anymore