Why Isn't Constructor A Requirement For Creating Objects
Jun 13, 2014
Java Code:
class GenericQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void push(E element) {
list.addFirst(element);
}
public E pull() {
return list.removeLast();
[code]...
Is a constructor required to create an object, if one of its instance or class variables haven't been instantiated? Like private String string;
I want to create a simple app that takes a name from the console then compares the name to a small phone book,when the name matches another name it will return the associated phone number.
I have a small contacts class which has name and number fields,Then I have a phone book class which populates an array with 4 contact objects that I can compare the entered number against.
here is my contacts class
public class Contact { String name; int number;
[Code].....
In the main method I am just trying to print out one of the fields for one contact to see if I can actually access it to compare it to the name entered.Its saying "MaryJones" cannot be resolved to a type.I'm guessing I cant create all that code in the constructor?
import java.util.ArrayList; public class LectureRoom{ private String courseName; private String roomNumber; private String Lecturer; private ArrayList <Student> studentList;
[Code] .....
Question:
Given the following BlueJ class diagram
Lecturer class (same with previous lab, no changes needed) Student class (same with previous lab, no changes needed)
LectureRoom (changes occurs here)
1. LectureRoom has roomNumber (e.g. A301), courseName (e.g. Java), lecturer (a reference to a Lecturer object), and studentList (a reference to an ArrayList that stores Student object). 2. LectureRoom has a constructor that receives courseName, roomNumber, and Lecturer. The constructor then sets/assign the courseName, roomNumber and Lecturer. This constructor also creates the studentList arraylist object.
I thought you can only create a new object using private implementations and then using a constructor to set your arguments inside the parameters of the constructor to the instance variables but how come he created an object without any private implementations and just methods inside the constructor.
import javax.swing.JFrame; public class MyWindow extends JFrame { public static void main(String[]args){ new MyWindow(); } public MyWindow(){ setSize(500,500); setVisible(true); setTitle("MyWindow"); } }
Its written that every constructor calls its super class constructor. And we know, constructors are called to create an object. Does it mean that if I am creating an object of a class, I am actually creating objects of all its super class???
The experiments will slowly converge towards one big experiment: a simple game. I have just a little interest in games (perhaps I should have more), but making one - even a simple one - should be self rewarding.
However, now to the point.
* The experiment creates an array of rectangle objects. * The rectangles are painted inside a Frame object at random x,y coords generated by a random number generator * The rectangles are stationary. * The rectangles are each assigned their own random colour. * The array of rectangle objects is created inside the constructor of the class.
The actual code contains various other variables and methods which would distract from a quick analysis, so below is code which has the same logical structure which also fails (instead of array of rectangles, I have used arrays of integers).
import java.util.Random; /** * Experiment 14 - see if it works simply - (with integer arrays) */ public class TestingArrays { // instance variables int N = 10; // the size of the array - 10 elements int[] a;
I finished a game in Java and sent it to a friend. Launching the program in my computer worked just fine.
But he got this error : "Could not find the main classs: Main. program will exit"
My JRE version is the most updated one. His JRE was version 1.6. He updated his JRE, and the problem was solved.
This is a bit worrying for me, because as far as I know, 1.6 isn't a very old version of the JRE. It's not the most recent one, but not that old.
This is worrying because I'm planning on sending my game to a lot of friends, and trying to distribute it on the internet.
A lot of people don't have the most updated JRE. And they are mostly non-programmers, so I can't expect them to update to the newest version of Java upon downloading my game. They might not know what Java is, even though they got it on their computer, and upon receiving an error, they'll just give up on the game.
If my game wouldn't work with a significantly old JRE, that would be reasonable. It's part of the nature of working with Java. But the fact that a relatively updated JRE, 1.6, doesn't work with my game, is worrying.
*(Please note: My game isn't implementing anything "special". Swing and KeyBindings are the 'newest' additions to Java that I can think of inside my game)*.
In short, I'd like to know that my game works on most of the computers it tries to run on. Knowing that it doesn't work on a relatively new JRE, is worrying.
So I have two questions:
1. Is it normal, for a Java program, to have such "high" demands for the JRE version? Do a lot of Java games demand at least version 1.6 of the JRE? Is this common?
2. How can I find out the minimum JRE version requirement for my program? Is there a methodical way to do this, or do I just have to go through all the libraries I use in my game and figure out what's the JRE release version for each one?
public class demo { Public class static void main(String[]args) { //Creating a variable that will be a reference to the object Peoples person_one;
[Code] ....
I have assembled this code below that has a void method which will creat a new object. Problem I encounter is that in
Create_object(person_one);
the person_one has an error saying not initialized. I'm jus trying to learn on my own ways here and practice so may know what's wrong with this? I know I can use a return object from methods but what about this approach?
I'm trying to create complex Character objects. Each object has a name, and for each object with the same name, they share some of the same initial data. However, there are also some bits of data that are given to the object when it's created. For example, an "Elephant" always starts out having a weight of 500, but its position is determined when it's created. Any of these values may later be changed during runtime.
class CharacterStaticParameters { int weight; int numberOfFeet; int numberOfEyes;
[code]....
For example, whether I should try to use words other than 'static' and 'dynamic', or a nicer word than 'parameters'?
So I'm still trying to get to grips with Java, and like to understand exactly why I'm doing something, so that I am not just regurgitating the code, If I want to create an object from class "Apples", I would use the following, right?
Apples MyAppleObject = new Apples();
From what I understand, MyAppleObject is the new object name, new -> creates a new instance of it in memory, and Apples() is the onCreate method that is called
So question 1: (just a quick aside question) Can I create an object without calling Apples()? i.e.
Apples MyAppleObject = new;
Question 2: - PARTLY SOLVED - I discovered that (Button) is a way of typecasting, so I understand that line a little better. What I don't understand is why we don't need to initialize the object with "new"
I've now looked at a bit of android development and xml and those declarations are all together different, and I'm not sure why. I haven't found a single explanation for the difference in format.
Java Code:
Button Add; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Add = (Button) findViewById(R.id.button1); mh_sh_highlight_all('java'); So the Button object is declared above the onCreate method, but initialized afterwards I guess....
But instead of using Button Add = new Button() they use Add = (Button) findViewById(R.id.button1);
Question 3:
then In XML they use the following:
Java Code:
public*static*void*main(String[] args){ ********* ********// Creates a DOM object in memory. Now you can access ********// data in the xml file ********* ********Document xmlDoc = getDocument("./src/tvshows5.xml"); mh_sh_highlight_all('java');
Once again, why didn't they have to use : Document xmlDoc = new Document()
I want to make a program where users are prompted to enter a username and a password and have these two values create a new instance of the Object User. But I'm not sure where to start.
import java.util.Scanner; public class Main { public static void main(String[] args) { createUser();
[Code] ....
how to take username + password and put it into an object.
I'm trying to create a simple bar chart from integer values (measuring number of bulldozers) stored in a mySql DB, in the following schema:
Integer rigId PK; Integer rigQty; Date recordDate; String country FK;
I want to plot the date on the x-axis and quantity on y-axis. I can't seem to find any examples of how to render charts from a database. I just find the generic Primefaces 4.0 examples which uses static data like this:
private void createCategoryModel() { // category chart categoryModel = new CartesianChartModel(); ChartSeries boys = new ChartSeries(); boys.setLabel("Boys");
[Code] ....
I'm really not sure how to adapt the above to a database method nor have any web searches produced useful examples. I tried something like this, but how to find examples or the type of methods I need to use to create a bar graph from Db values:
@ManagedBean(name = "chartb") @SessionScoped public class BarChartBean { private final Map<Integer, Map<String, Number>> rigNums = new HashMap<>(); // private final Map<Integer, Map<String, Number>> HorasOrcadasPorFunci = new HashMap<>(); private CartesianChartModel cartesianChartModel;
I've been trying to write a program for some time now, but im encountering problems while trying to complete it. The program has a student class and a course class (set up with some info about the class, like #, professor name, course title, course time). Now, i have a text file in the workspace, and i have to import the data from the textfile, and thats just what i did, but then there is an option which allows the user to delete a course only by inputing the course number, and when he does that, the program outputs the course's name, and confirms the deletion of the course (From the student's record, i created a vector for that and imported all the courses from the text file). But how can i let the program know what's the name of the course when the user inputs the course number ???
When the data is read from the file, objects should be created and added to the student's course record. <- i think here's where i messed up ? i imported the data, but how can i actually make them objects before adding them into the vector ?
PHP Code:
public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); Vector Record = new Vector(); try {FileReader filereader = new FileReader("CLASSES.txt"); BufferedReader bufferedreader = new BufferedReader(filereader); String test = ""; while(test != null) { Record.addElement(test); test = bufferedreader.readLine(); } mh_sh_highlight_all('php');
I've a parent class with a argument constructor like below(a sample code)
public class Parent { Parent(String name) { System.out.println(name); } public static void main(String[] args) { } }
Also I've child.class which extends Parent.class as shown below,
public class child extends Parent { child(String name) { super(name); } }
Now, I want create/modify the constructor which is in child, by taking "int i" as an input instead of "String name". How can I do that? Run time I want to execute child constructor not a parent constructor.
Condition is: Without making any changes to the Parent class
I am currently working on a project where I need to return data from a database over RMI to a client who requests it. Some of the fields in the Data Object can not be seen by the client so I need to create another object to send over the network instead. The method I use is this...
public static SerializableObject createSerializableObjectFromDataObject(DataObject dataObject){ SerializableObject serializableObject = new SerializableObject(); serializableObject.setField(dataObject.getField()); serializableObject.setAnotherField(dataObject.getAnotherField()); return serializableObject; }
Is there a better way of doing this? I am creating many subclasses DataObject which all require this static method to be implemented and I can't push it into the superclass because each one needs custom behaviour.
I was practicing my java skills and came across an exercise in which a non parameter constructor calls a two parameter constructor. I tried a few searches online but they all came back unsuccessful. This is the part I am working on:
public PairOfDice(int val1, int val2) { // Constructor. Creates a pair of dice that // are initially showing the values val1 and val2. die1 = val1; // Assign specified values die2 = val2; // to the instance variables. } public PairOfDice() { // Constructor that calls two parameter constructor }
I tried calling the two constructor using the line "this(val1, val2)" but I get an error because val1 and val2 are local variables.
Then I tried to use the same signature: "this(int val1, int val2)" but that didn't work either.
how String objects are different from other objects
part 1:
// creating two objects Dog mydog1 = new Dog(); Dog mydog2 = new Dog(); // comparing the reference variables if( mydog1 == mydog2){ System.out.println(" The reference variables refer the same object "); } else { System.out.println(" They refer to different objects "); }
The above code works as I understand objects , it prints "They refer to different objects " to the screen.
Part - 2
// creating two objects ( I beleive, pls correct me if i am wrong ) String a = "haai"; String b = "haai";
if( a == b){ System.out.println(" Reference variables refer to same object");
When i run the above code it prints that a and b refer same object , I don't understand how they refer to same object when i didn't assign " String b = a; ". My question is did java just create one object and stored the same reference values to a and b .
I'm wonder about the issue of constructor for arrays. Let say I have a class tablica, and one component int[] tab. If I get it right until now tab is nothing more than empty reference to some unexisting array?
import java.util.Random; class tablica{ int[] tab; tablica (){ // i wish it was constructor
[code]....
Then, I'm trying to build the constructor for class tablica. What can be the parameter of such constructor? Is it fields of array? It is simple forf for basic variable
- I liken values defined in constructor with those global defined in class. But how to do it with array component tab.
If I create array object in main method then how can I use this constructor?
public class TestClass { public TestClass(String k){System.out.println(k);} public static void main(String[] args) { try { hello(); } catch(Exception e){System.out.println(e);}
[Code] ....
Explain how to catch block act as constructor with parameter?
"A constructor cannot be abstract, static, final, native, or synchronized."
I understand on why it can't be all of the above, except "final".
Why can't we have a final constructor, i understand constructors are not inherited, hence no chance/case of overriding etc. But why is it not allowed at all ?
So I am working on a school project and I have 2 classes, class FakeGravity contains all the properites and class BouncyBall is my driver class. For some reason when I try writing
FakeGravity gravity = new FakeGravity( );
I get an error. I am attaching an image of the error, and also attaching the program just in case you need more information. Also I was using blueJ to write the program
dcasarrubias, on 27 October 2014 - 02:44 PM, said:
So I am working on a school project and I have 2 classes, class FakeGravity contains all the properites and class BouncyBall is my driver class. For some reason when I try writing
FakeGravity gravity = new FakeGravity( );
I get an error. I am attaching an image of the error, and also attaching the program just in case you need more information.