Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to java in general but I am having a lot of trouble with objects specifically. I have a project to pass an object to another object. I've looked all over the internet for help, my online java textbook doesn't explain objects in detail. So my question is, how would you pass an object to another object.
-Thank you in advance
Messaging between objects is a core concept in object-oriented programming. To "pass an object to another object" generally just means that one object exposes a method which accepts the type of another object as a parameter to that method. It could be something as simple as this:
class Person {
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
class Car {
private Person driver;
public void setDriver(Person driver) {
this.driver = driver;
}
}
Then somewhere in the code, you'd have an instance of a Car and an instance of a Person, and you'd call that method:
carInstance.setDriver(personInstance);
Those instances could have been created lots of different ways. Perhaps even as simple as:
Person personInstance = new Person();
personInstance.setName("David");
Car carInstance = new Car();
You can pass an object o1 to another object o2 through calling a method of o2 (or a constructor of o2's class in particular; constructors as you know are special types of methods).
I suggest you start by figuring out what this code below does.
How many persons are there?
What are their names at different moments of the execution of the program?
How many times and where a Person object is passed to a Person object?
How many times and where a String object is passed to a Person object?
If you digest this, you'll be good for now.
class Person {
private String name;
public Person(String name){
this.name = name;
}
public Person(Person p){
this.name = p.name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class MainProg {
public static void main(String[] args) {
Person t1 = new Person("Joe");
Person t2 = new Person("John");
System.out.println(t1.getName());
System.out.println(t2.getName());
t1.setName("Mark");
System.out.println(t1.getName());
System.out.println(t2.getName());
Person t3 = new Person(t1);
System.out.println(t3.getName());
}
}
Related
I want to retrieve the reference variable name.
This works fine
MyClass c1=new MyClass("A0001");
c1.myMethod(c1);
System.out.println(c1.Persons.get(0).Name); // output is: A0001_1
The classes are:
class MyClass{
public List<Person> Persons = new ArrayList<Person>();
public String name="";
MyClass(String name){
this.name=name;
}
void myMethod(MyClass c){
Persons.add(new Person(c));
}
}
class Person{
public static int Num=0;
public String Name="";
Person(MyClass c){
Num++;
this.Name=c.name+"_"+Num;
}
}
but I want it to be like this
MyClass c1=new MyClass("A0001");
c1.myMethod();
System.out.println(c1.Persons.get(0).Name);
class MyClass{
public List<Person> Persons = new ArrayList<Person>();
public String name="";
MyClass(String name){
this.name=name;
}
void myMethod(this){
// which Reference Variable calls this method?
System.out.println("name of the Reference Variable="+???);
Persons.add(new Person(this));
}
what can I put to ???
how programmatically can we show "c1" in ???
There is no reason to pass same object as parameter to its own method.
Also, there is no reason to make a method to accept another object of the same class as parameter to create Person object.
so if your Person object always creates by MyClass object and needs exact that MyClass object as constructor parameter, do this:
void myMethod(){
Persons.add(new Person(this));
}
I'm not sure to understand your need.
First, your question title makes me thing you want to use the injection/reflexion capabilities of Java.
Based on your code and explanations, I doubt you're looking for this complexity.
Second, this part is unclear. How the hell can we guess what you're trying to do here ?
void myMethod(){
MyClass c=??? // WHAT DO YOU WANT TO DO ?!!!!
Persons.add(new Person(c));
}
What you want is the constructor of Person1 class to decide of a Class to put the person in ?
If yes, something like this could do the trick (kindof a factory ?)
The MyClass keeps track of all create classes.
Besides, i guess that your class should be able to receive Person and Person1.
Code written oustide of IDE, some mistakes might been still here.
And once again, this is based on a partial understanding of your post.
class Person1 extends Person {
Person1() {
MyClass c= MyClass.getTheClass("My_Awesome_Class");
this.Name=c.name+"_"+Num;
c.addPerson1(this);
}
}
With:
class MyClass {
// keep track of created classes
private static HashMap<String,MyClass> classMap = new HashMap<String,MyClass>();
public List<Person> Persons = new ArrayList<Person>();
public String name="";
private MyClass(String name){
this.name=name;
}
void addNewPerson() {
Persons.add(new Person(c));
}
void addPerson1(Person1 p) {
}
// lazy factory
public static MyClass getTheClass(String classname) {
// class does not exist yet
if (! classList.containsKey(classname)) {
//create it
MyClass theNewClass = new MyClass(classname);
classList.put(classname, theNewClass);
}
return classMap.get(classname);
}
}
Your code becomes:
// MyClass constructor is no longer directly visible ...
MyClass c1 = MyClass.getTheClass("A0001");
c1.addNewPerson();
System.out.println(c1.Persons.get(0).Name);
Person1 my_pupil = new Person1(); // creates My_Awesome_Class if needed
MyClass c2 = MyClass.getTheClass("My_Awesome_Class");
System.out.println(c2.Persons.get(0).Name);
EDIT:
some answers pointed out that maybe you want the Person classes to have visibity on their Class. Someone answered that part : pass the Class as argument of Person constructor.
EDIT2:
well the question has changed since my post ...
In Java objects are mostly created on heap memory ,so we don't have name for objects in Java
You can get a hash Code by using this.hashCode();, this is not the address of your object in the heap , we don't get object's address in java
so you can get the name of the class from the object by using this.getClass().getName
Note: when we write MyClass c1=new MyClass("A0001"); , c1 is not the object of class MyClass its a Reference to the instance of class MyClass
To know more about it Check answer in the Following link
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a little code that let me register an student (ID, name, age, etc), right now I could do it but just accepting one user, would overwrite if I register a new one, which is what I need now, be able to have more than 1 student.
So I was thinking that if I were using C I would use structs, something like this
struct Students {
int ID[6];
char Name[35];
char Age[2];
} student;
After reading a bit, Java doesn't have this facility.
How to do this in Java ? Is it possible ?
Thanks
Java has no struct.
You can use class as structs with members having public access specifier and no methods
In Java you could make a class for students. Once you get to know java better you should change those properties to either private or protected and use public getter/setter methods.
public class Student{
public int id;
public String name;
public int age;
}
And then in your main code you could create however many students you need:
Student myStudentA = new Student();
It is true that in C you would use structs to embody the information you need for each student.
In object-oriented languages like Java, you would use classes. So the equivalent to the C structure you defined would be something like the following class in Java:
public class Student
{
public int id; // [*]
public String name;
public String age;
//... other things go here, such as constructors and methods ...
}
[*] You defined the id member to be an array of 6 integers. I assume that you probably meant it to be a single integer value that could hold up to 6 digits.
You probably also want to define the age member to be a integer instead of a two-character string.
Note that in Java, String variables do not have a maximum length like null-terminated C character arrays do.
It is absolutely possible to do this in Java. Java is an object oriented programming language so when you are dealing with "things", such as students, it is very easy to implement them into a Java class.
Here is one of many ways you could do this:
public class Students{
private List<Student> students;
public Students(){
this.students = new ArrayList<>();
}
public void addStudent(Student newStudent){
students.add(newStudent);
}
public Student getStudents(){
return this.students;
}
public Student getStudent(int name){
for(Student s : students){
if(s.getName().equalsIgnoreCase(name)){
return student();
}
}
return null;
}
public class Student{
private int id;
private String name;
private int age;
public Student(){
}
public Student(int id, String name, int age){
this.id = id;
this.name = name;
this.age = age;
}
// Getters and Setters for the Students variables
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What is the difference between this and .this when calling functions? And, what happens when this or this. is used?
Example:
class reference
{
public void object()
{
reference obj = new reference();
this.obj();
}
}
The Class.this syntax is useful when you have a non-static nested class that needs to refer to its enclosing class's instance.It is only used in cases where there is an inner class, and one needs to refer to the enclosing class
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
A good example
public class TestForThis {
String name;
public void setName(String name){
this.name = name;
}
public String getName() {
return name;
}
class TestForDotThis {
String name ="in";
String getName() {
return TestForThis.this.name;
}
}
public static void main(String[] args) {
TestForThis t = new TestForThis();
t.setName("out");
System.out.println(t.getName());
TestForThis.TestForDotThis t1 = t.new TestForDotThis();
System.out.println(t1.getName());
}
}
Output will be
out
out
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to know the exact scenario of using constructor over methods can anyone give me the exact example program for constructors over methods in java
They are not similar things to compare even.
Both serves completely different purposes and even you have to note that constructor wont return anything, not even void :)
If you see a basic tutorial on Constructor, mentioned
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
So you cannot choose one over them.
If you are looking/talking about setting variables of instance memebers, choose setter methods instead of variables.
Another scenoriao is some objects never complete without providing some basic info. In that cases you have to create a constructor like it should be built when necessary info passed in constructor.
Consider the below scenorio, where to create an employee class, He must have an employee Id
public class Employee {
String empId;
public Employee(String empId) {
this.empId = empId;
}
// Methods
public static void main(String[] args) {
Employee a = new Employee("green");
}
Consider the below scenorio, where to create an empty employee class, later he can assign employee Id
public class Employee {
private String empId;
public Employee() {
}
// Methods
public void setEmpId(String empId) {
this.empId = empId;
}
public static void main(String[] args) {
Employee a = new Employee(); //No error
a.setEmpId("SOMEX007");
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have to create a collection of Name,Address,Age.How do I create this as a collection object in java.
My snippet is as follows:
public class DataCollection implements java.io.Serializable{
private String Name;
private String Address;
private int Age;
}
And I have the getter and setter methods...
In the main method, how do I create this as a collection??
list.add(new DataCollection(??????) );
Can someone please help me on this?
public class DataCollection implements java.io.Serializable{
private String Name;
private String Address;
private int Age;
public DataCollection(String name, String address, int age){
this.Name=name;
this.Address=address;
this.Age=age;
}
}
After that create DataCollection objects:
DataCollection d1 = new DataCollection("nik", "10/5 cross", 20);//creation of List collection
Now put the object inside a collection:
List<DataCollection> list = new LinkedList<DataCollection>();
list.add(d1);
You can iterate like below:
List<DataCollection> list=new LinkedList<DataCollection>();
for(DataCollection d : list){
System.out.println(d);
}
It is not clear from your question exactly what you are asking. I suspect the problem is that you are trying to allocate a List, which is an abstract class. You should be allocating a LinkedList or an ArrayList, or something of that sort. For a minimal example:
import java.util.List;
import java.util.ArrayList;
public class DataCollection implements java.io.Serializable{
private String Name;
private String Address;
private int Age;
public static void main(String[] args){
ArrayList<DataCollection> list = new ArrayList<DataCollection>();
list.add(new DataCollection());
}
}
Then you can use list.get(index) to access the item in the list and set a name. The other problem may be that you want to pass arguments in when you create the object (such as the name, address, and age. If that is what you want to do, you need to look up overloading constructors.