This question already has answers here:
How can a class have a member of its own type, isn't this infinite recursion?
(7 answers)
Closed 6 years ago.
Class Person {
Person name;
Person age;
..
}
In this usage , what does it mean Person name and Person age. Of course name and age data type is Person but I cannot understand the concept how will I use in my program.
For example
if I Person data type replaced by String name and int age , I will use in main method like:
Person p1 = new Person();
p1.name = "blabla";
p1.age = 30;
But how will we use the Person data type like that.
I have already searched on the Internet but I couldn't find anything about that.
This is a bad (catastrophic) design decision.
Instead it should look like
class Person {
String name;
int age;
}
There are possibilities when using Person within Person would be justified. Look at the following examples.
class Person {
Person manager; // Here, an employee could have another Person being its manager
}
class Person {
Person partner; // Here, a person could be married and have another Person as partner
}
Related
it's maybe a newbie question but I think it will be helpful for some beginners.
My question is :
public abstract class Person {
code goes here ....
}
public class Employee extends Person {
code goes here ....
}
What is the difference between those kind of instantiation ?
Person student = new Employee("Dove","Female",0);
and
Employee student = new Employee("Dove","Female",0);
They are essentially the same, but the compiler treats Person student as a Person without any type information from the concrete class Employee
It's basically the same thing, but the difference is that:
1- In the first declaration:
Person student = new Employee("Dove","Female",0);
Here student can't access Employee class specific methods or attributes as it's a Person object which contains an Employee instance.
2- But in the second one:
Employee student = new Employee("Dove","Female",0);
Here student can benefit from both Employee and Person attributes and methods.
Please check Polymorphism Oracle Docs for further reading about polymorphism in Java.
Example:
We can see that in this example, where we use Integer and Object classes:
Integer i1= new Integer(0);
//This will run and execute perfectly
System.out.println(i1.intValue());
Object i2= new Integer(0);
//This will throw an error as `Object` class doesn't have `intValue()` method.
System.out.println(i2.intValue());
This is a live working Demo so you can see that.
Following is difference in both instantiation.
(1)
Person student = new Employee("Dove","Female",0);
In this instantiation student is object of Person class so it can't access Employee class specific methods or attributes.
(2)
Employee student = new Employee("Dove","Female",0);
Here, in second instantiation student can access Employee class specific methods and attributes as well as Person class because it is extending in Employee class.
This is basic difference in this two statements.
This question already has answers here:
Comparator.comparing(...) of a nested field
(4 answers)
Closed 4 years ago.
In Java 8 Comparator, we can create a comparator as follows.
Comparator.comparing(keyExtractor);
Currently I have a class as follows
class Employee {
String name;
Department dept;
}
class Department {
String departmentName;
}
Now, if I want to create a comparator for Employee class which sorts the records based on the department name, how can I write my key extractor?
Tried the below code, but did not work.
Comparator.comparing(Employee::getDept::getDepartmentName);
You can use function that extracts a sort key
I.e.
Comparator.comparing(Employee::getDept,Comparator.comparing(Department::departmentName));
The trick here is method references are not objects and don't have members to access. So you can't do this:
Employee::getDept.getDepartmentName
Moreover, method references are not classes, so you can't get another method reference from them. So this also fails.
Employee::getDept::getDepartmentName
Finally, the only option that is left with us is this.
e -> e.getDept().getDepartmentName()
Try this out,
Employee empOne = new Employee("Mark", new Department("Accounts"));
Employee empTwo = new Employee("Melissa", new Department("Sales"));
List<Employee> employees = Arrays.asList(empOne, empTwo);
employees.sort(Comparator.comparing(e -> e.getDept().getDepartmentName()));
employees.forEach(System.out::println);
I missed one of my lectures in Java, and the subject was classes, methods, constructors etc. The homework is one task:
Create a class Person, objects of which describe persons, and which
contains only two felds: name (String) and year of birth (int). In
this class, define
constructor taking name and year of birth;
constructor taking only name and setting the year of birth to default value 1990;
method isFemale returning true if this person is a woman (we assume, not very sensibly, that only women and all women have names ending
with the letter 'a'); otherwise the method returns false;
static function getOlder taking two references to objects of class Person and returning the reference to the older of these two persons;
static function getOldest taking the reference to an array of references to objects of class Person and returning the reference to
the oldest person represented in the array;
static function getYoungestFemale taking the reference to an array of refe- rences to objects of class Person and returning the reference
to the youngest woman represented in the array, or null if there is no
woman in the array.
In a separate class, write a main function in which the whole
functionality of the class Person is tested.
I checked some tutorials and explanations, I didn't go straight here asking for help but after 2 hours of ripping my hair out I've been only able to come up with this:
public class Person {
String name;
int yob; //year of birth
public Person() {
Person jan = new Person("Jan", 1995); //the names are polish
Person joanna = new Person("Joanna", 1993);
Person michal = new Person("Michal", 1980);
Person beata = new Person("Beata", 1979);
Person kazimierz = new Person("Kazimierz", 1998);
Person magdalena = new Person("Magdalena", 1999);
}
public Person(String name, int yob) {
this.name = name;
this.yob = yob;
}
public Person(String name) {
this.name = name;
this.yob = 1990;
}
public static boolean isFemale(String name) {
if(name.equals("Joanna")) {
return true;
} else {
return false;
}
}
public static String getOlder(Person x?, Person y?) { // if I understand the task correctly, I should reference any two names?
if(x?.yob>y?.yob) {
return x?.name;
} else {
return y?.name;
}
//getOldest and getYoungestFemale methods go here
}
}
However, I can't wrap my head around the last three steps. My brain is literally boiling. It would really help if anyone could explain the last three bullet points (getOlder reference to any 2 people and getOldest/getYoungestFemale)
If you don't have time to explain, some example of a "method taking a reference to an array" should be enough for me to get a basic understanding.
Thanks in advance.
Usually.. you don't call it "reference to an array of references of something" You just say "array of something". Even though arrays of objects are arrays of references to objects. Just like a variable for an object is just a reference to an object.
Type heyImAReference = new ImTheObject();
So when you write
Person person = new Person();
You'll have the class Person as type, person as a reference to an instance (or object) of that class and the resulting entity of new Person() as the actual thing that is being referenced. Usually called "instance" or in your case "object".
When it comes to arrays of persons and you do
Person[] persons = new Person[5];
You create via new Person[5] an array instance that has 5 slots, in each slot can go a Person instance figuratively, actually though you have 5 references. Person[0] being the first, Person[1] being the second and so on. So that is an "array of references to objects of class Person".
And persons is a reference to that. So it is a "reference to an array of references to objects of class Person"
static function getOldest taking the reference to an array of references to objects of class Person and returning the reference to the oldest person represented in the array
means nothing more than
static Person getOldest(Person[] persons) {
...
}
I would call that a method that takes an array of Persons and returns a Person. Though technically, it's all just references that go in and come out. The Person objects don't "move"
Firstly create another class which will have main method. Within main create an array:
Person[] parr = new Person[6];
//Then fill all your person to this array:
parr[0] = new Person("name", year);
parr[1] = ....
Then pass this array handler to your methods:
Person p1 = Person.findSomething(parr);
In Person class:
public static Person findSomething(Person[] parr){
for (Person p : parr){
if (p.name.endsWith("a")) return p;
}
return null;
}
Here are some hints which should help you work out the answer yourself without me giving away the solution ;)
1)
public static String getOlder(Person x?, Person y?) {
// if I understand the task correctly, I should reference any two names?
if(x?.yob>y?.yob) {
return x?.name;
} else {
return y?.name;
}
}
This code is almost correct! Just remove the question marks! Also remember that the older person will have an earlier yob. EDIT, also you need to return the reference to the person, not their name, so return either x or y.
2) getOldest and getYoungestWoman
Person[]
is an array of references to Person objects. You should be able to read up on how to loop through the elements of an array and compare values.
3) an extra: if you declare those 6 Person objects inside the constructor, you won't be able to access them in other methods of the class. it is ok to create the Person objects there, but you must declare them outside the constructor. Declare them in the class.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hi I'm unsure how I go about referencing objects to my arraylist.
The class where im declaring the arraylist:
Any help would be much appreciated
First of all name is not static so you can not access it as Student.name only instance of student can access it if it's public.Now, you want to construct the Student than you should pass the name of student in constructor.You can declare getter and setter methods for your Student attributes.
Moreover ArrayList.add can be used to add your Students to your list and you better not add students in constructor use different method to write this scenario.
FOR EXAMPLE :
Student student = new Student("NewStudent");
System.out.println("Name of student :" +student.getName());
studentList.add(student);
Regarding:
public TutorGroup() {
super();
Student student = new Student(Student.name); // this makes no sense
studentList.add(student.Student(name, tmaMark));
}
I'm not sure what you're trying to do with new Student(Student.name) since it isn't clear what this code is trying to do, but regardless, the compiler is right -- it shouldn't exist, and so get rid of it.
Delete this TutorGroup constructor and re-do it. How you re-do it will depend on where your TutorGroup is to get the Student objects. If they're going to be packed into an ArrayList and then passed in, then give TutorGroup's constructor an ArrayList<Student> parameter, and when calling the class, pass in the list. If you will add Students one at a time, then make the constructor simple (or get rid of it), and give the TutorGroup class an addStudent method:
public void addStudent(Student s) {
studentList.add(s);
}
In your TutorGroup constructor your trying to pass the value in the name variable in the Student class which you cant access because 1. The name variable is private so only members of the class have access to it. and 2. It doesn't hold a value yet since that's what your trying to pass into the Student constructor.
What you should do is pass a string literal into your Student constructor like: new Student("Jamie") then it will be saved in the name variable in your Student class, and if you need to access the name later add a public method in your Student class that returns the value in your name variable.
Your code has several issues.
Firstly the Student class should have some getter methods, so that you can access the data from a student object:
public String getName() {
return this.name;
}
public int getTmaMark() {
return this.tmaMark;
}
For creating a student object with the correct data, you have 2 options:
Option A) Create a constructor for Student that takes both values:
public Student(String aName, int aMark)
{
super();
this.name = aName;
this.tmaMark = aMark;
}
Option B) Create setters for your Student class
public void setName(String aName) {
this.name = aName;
}
public void setTmaMark(int aMark) {
this.tmaMark = aMark;
}
You can, of course, implement both options in Student, giving you extra flexibility.
Then, to add a new Student to your ArrayList, you can simply create a student and use the array's add method:
Examples:
ArrayList<Student> studentList = new ArrayList<Student>();
// Create student using constructor
Student studentA = new Student("Alice", 15);
// Create student using setters
Student studentB = new Student();
studentB.setName("Bob");
studentB.setTmaMark(10);
// Add both students to the ArrayList
studentList.add(studentA);
studentList.add(studentB);
Please remeber that for the studentB example, if you added a constructor with arguments to your Student class (Option A) you also need to create an explicit default constructor (without arguments).
Im not sure exactly what you are trying to do. I am going to assume you want to add a student into the ArrayList called student list. The line Student student = new Student(Student.name); is creating a new object of type Student called student but you are not passing into any parameters into the constructor for the student class, but it requires a String which is used as the name. What you want to do (i think) is add a student to your array list. As your ArrayList has type student the method to add student x should be
public void addStudent(Student x)
{
studentList.add(x);
}
Where Student x is passed as a paramater to the addStudent method. To Create a new student with the object name newstu and the name nameOfStu you could do this.
Student newstu = new Student(nameOfStu);
addStudent(newstu);
I hope this helps.
I need a function to take a name and return the details of the record associated with that name.How do i do this? I have all the info. in my result set, but i need a way to pass it to one variable and return the value in java. I am using eclipse-juno under CentOS
If you have a Person class with fields Name,Address and Age and I am assuming you want to find all the details of a Person given his/her Name, you can write a method that returns an object of Person class like this:
//Assuming Person class is declared with all fields and/or appropriate setters-getters.
//create a method to get all the details of a particular person based on name.
public Person getPerson(String name){
//get all the details from the database in a resultset rs
//Create a new object Person class
Person p = new Person();
//set the details from the resultset to this newly created Person object
p.setName(rs.getString("name");
p.setAddress(rs.getString("address");
p.setAge(rs.getInt("age");
//now your Person object is ready with all the details that you need, you return it to callinh method
return p;
}
You can use this returned Person object using getters to access the fields.