How do I resolve wrong output error in java aggregation? - java

My code is working fine, but in the output, both employees are having same address. Why is it happening so and how can I resolve it?
package practice;
class address{
static String country,state,cityname;
public address(String country, String state, String cityname) {
this.country=country;
this.state=state;
this.cityname=cityname;
}
}
class employee{
String name;
int id;
int age;
address add;
public employee(String name, int id, int age,address add) {
this.name=name;
this.id=id;
this.age=age;
this.add=add;
}
void display() {
System.out.println(name+" "+id+" "+age);
System.out.println("the employee stays at"+ address.country+" "+
address.state+" "+address.cityname);
}
}
public class Document {
public static void main(String[] args) {
// TODO Auto-generated method stub
address a2 = new address("A","B","C");
address a1 = new address("D","E","F");
employee e1 = new employee("lmn",123,20,a2);
employee e2 = new employee("pqr", 456,24,a1);
e1.display();
e2.display();
}
}

The problem is the static variables in address:
class address{
static String country,state,cityname;
...
remove the static keyword.
Also make your properties private and add getter and setter.
Take care of java naming conventions. Class names should start with upper case character

Related

how to build a set of accessors that retrieve declared datas

public class student {
public static void main(String[] args) {}
private String name;
private String Idnumber;
private String DOB;
private String Gender;
private String Address;
private String schoolname;
private int Grade ;
private double GPA;
public student() {
name = "ABC";
Idnumber = "12345678";
DOB = "1-1-1999";
Gender = "male";
Address = "123 Main Street";
schoolname = "ABC";
Grade = 99;
GPA = 4.0;
}
}
This is a default constructor that I had to built now I'm trying to build the accessors.
Sorry for any mistakes in the code, I'm a beginner.
Accessors are a simple concept: each variable that is declared in your class (e.g. name, Idnumber, etc.) should be a private variable that requires a getter and setter method. For example:
public class Student
{
//Declare private variables here.
private String name;
//Constructor.
public Student()
{
name = "ABC";
}
//Method to access the "name" variable.
public String getName()
{
return name;
}
//Method to set a new value to the "name" variable.
public void setName(String name)
{
this.name = name;
}
}
In a similar way you would create a getter and setter for all other variables as well. You would need to ensure the correct variable types are used each time (e.g. private int Grade; will have a public int getGrade() {...} and also a public void setGrade(int grade) {...}.
You may also want to ensure the names of all classes start with a capital letter (e.g. Student) and the names of all variables utilize camel-case format so they begin with a lowercase letter (e.g. gender, address, etc.) as it is common practice to do so.

Class Level Variable Eligible for GC in Java

I have an Employee, an Organization and Test class. The employee contains information related to Employee and Organization class contains Employee list. Please find below source code of both class:
Employee.java
package com.practice;
public class Employee {
private String empId;
private String name;
private int age;
private float salary;
public Employee(final String empId, final String name, final int age, final float salary) {
this.empId = empId;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getEmpId() {
return empId;
}
public void setEmpId(final String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(final float salary) {
this.salary = salary;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return this.empId + " " + this.name + " " + this.age + " " + this.salary;
}
}
Organization.java
package com.practice;
import java.util.ArrayList;
import java.util.List;
public class Organization {
private final List<Employee> empList = new ArrayList<Employee>();
Organization() {
}
public void addEmployee(final Employee emp) {
this.empList.add(emp);
}
public List<Employee> getEmpList() {
return empList;
}
}
TestGC.java
package com.practice;
public class TestGC {
public static void main(final String[] args) {
final Employee emp = new Employee("E1", "Emp 1", 20, 2000.0f);
final Employee emp2 = new Employee("E1", "Emp 1", 20, 2000.0f);
final Organization org = new Organization();
org.addEmployee(emp);
org.addEmployee(emp2);
System.out.println(org.getEmpList());
}
}
In Organization.java, we have list of Employee object and I have created the object in the same line, that means at class level. So, my question is, will that list be eligible for GC once I'm done with Organization object or it will be a leak in memory? Also, will it make any difference if I instantiate the same object inside constructor?
What you have are regular instance variables (as well as a few local variables). They will be collected normally, when they're no longer reachable. It makes no difference if you instantiate them from the constructors, it'll only add unnecessary code.
It's not that easy to leak memory in Java.
Will that list be eligible for GC once I'm done with Organization
object or it will be a leak in memory?
Yes. List will be eligible for the GC once organization object goes out of scope. All you are using are instance variables, so no need to worry about memory leak unless you have some static variables used in bad way.
will it make any difference if I instantiate the same object inside
constructor?
No.

Java ,import not resolved,inheritance,inner class

Begging java programming recently, run into an error. please help
Have two classes , PersonTest.java:
public class PersonTest {
public static void main(String[] args) {
Person person1=new Person("dummy","sdymmt","20","male","washington");
System.out.println("Name: "+person1.getName());
System.out.println("Surname: "+person1.getSurname());
System.out.println("Age: "+person1.getAge());
System.out.println("Gender:" +person1.getGender());
System.out.println("Birthplace: "+person1.getBirthplace());
Person person2= new Person(400);
System.out.println("Income:"+person2.getX()+" mije leke");
System.out.println("Tax:"+person2.Taksat()+" mije leke");
Student student1= new Student("adsd","zedsdsadza");
System.out.println("emri"+student1.getEmer());
}
}
and also Person.java :
public class Person {
private String Name;
private String Surname;
private String Age;
private String Gender;
private String Birthplace;
private double x;
public Person()
{
}
public Person(String Name, String Surname, String Age, String Gender, String Birthplace) {
this.Name = Name;
this.Surname = Surname;
this.Age = Age;
this.Gender = Gender;
this.Birthplace = Birthplace;
}
public String getName() {
return Name;
}
public String getSurname() {
return Surname;
}
public String getAge() {
return Age;
}
public String getGender() {
return Gender;
}
public String getBirthplace() {
return Birthplace;
}
public Person(double x) {
this.x = x;
}
public double getX() {
return x;
}
double Taksat() {
return (0.1 * x);
}
public class Student extends Person {
private String University;
private String Faculty;
public Student(String Universiteti, String Fakulteti) {
super(Name, Surname, Age, Gender, Birthplace);
this.Faculty = Fakulteti;
this.University = Universiteti;
}
public String getFaculty() {
return Faculty;
}
public String getUniversity() {
return University;
}
}
}
Two classes are in the same default package. How to fix the fact that the test class doesn't recognize the inner class student as a class.
Nested non static class are called Inner Classes those classes cannot live without the Outer class (which wrapped them).
Java docs
An instance of InnerClass can exist only within an instance of
OuterClass and has direct access to the methods and fields of its
enclosing instance.
To instantiate an inner class, you must first instantiate the outer
class. Then, create the inner object within the outer object with this
syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Try using:
Person.Student student = person1.new Student(PARAMETERS);
Important Mark:
Of course, you should highly consider that this is not a good design, because you may want this classes to be visible outside of the Person class but also because Person.Student inherits from Person, which it's already contains the Student class, which usually looks like a loop or a circle relationship, which usually not a good idea for the first place.
Because there is no Student class. Since it nested, it's Person.Student

retriving specific data from LinkedList

I want to find students whose gender is female by using streams
Student class
public class Student {
private String first;
private String last;
private int ID;
private Gender gender;
int next=0;
List<Course> courses=new LinkedList<>();
List<Student> students=new LinkedList<>();
public Student(String first, String last, int iD, Gender gender) {
this.first = first;
this.last = last;
ID = iD;
//this.gender = gender;
}
public void enroll(Course c) {
courses.add(c);
}
public void isFemale(){
Student s;
return s.gender=Gender.F;
}
}
enum class for genders
public enum Gender {
M,F;
private Gender gender;
}
main class
public class Main {
public static void main(String[] args) {
List<Student> studentsOfClass=new LinkedList<>();
studentsOfClass.add(new Student("john","smith",01,Gender.M));
studentsOfClass.add(new Student("mick","tayson",05,Gender.M));
studentsOfClass.add(new Student("sara","conor",04,Gender.F));
studentsOfClass.add(new Student("Tana","smith",02,Gender.F));
Course c1=new Course("fiologiya","anna",0234);
Course c2=new Course("mathematics","maria",1134);
Course c3=new Course("phisics","luisa",0534);
studentsOfClass.stream().limit(3).forEach(s->s.enroll(c1));
Collection<Student> femaleStudents= studentsOfClass.stream().filter(Student::isFemale).collect(Collectors.toList());
}
}
You are using the Stream methods correctly, but your isFamele method is wrong. It should return boolean and check the gender of the current Student.
It should be :
public boolean isFemale()
{
return gender==Gender.F;
}
You should also unremark this constructor line - //this.gender = gender; - and probably remove private Gender gender; from the Gender enum.
In addition, you can change the type of femaleStudents from Collection to List<Student>, which is more accurate.

How to use a variable of one class, in another in Java?

I'm just working through a few things as practice for an exam I have coming up, but one thing I cannot get my head round, is using a variable that belongs to one class, in a different class.
I have a Course class and a Student class. Class course stores all the different courses and what I simply want to be able to do is use the name of the course, in class Student.
Here is my Course class:
public class Course extends Student
{
// instance variables - replace the example below with your own
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
/**
* Constructor for objects of class Course
*/
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
}
And here is Student:
public class Student
{
// instance variables - replace the example below with your own
private int studentNumber;
private String studentName;
private int studentPhone;
private String studentCourse;
/**
* Constructor for objects of class Student
*/
public Student(int number, String name, int phone)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = courseTitle;
}
}
Am I correct in using 'extends' within Course? Or is this unnecessary?
In my constructor for Student, I am trying to assign 'courseTitle' from class Course, to the variable 'studentCourse'. But I simply cannot figure how to do this!
Thank you in advance for your help, I look forward to hearing from you!
Thanks!
Am I correct in using 'extends' within Course? Or is this unnecessary?
Unfortunately not, if you want to know whether your inheritance is correct or not, replace extends with is-a. A course is a student? The answer is no. Which means your Course should not extend Student
A student can attend a Course, hence the Student class can have a member variable of type Course. You can define a list of courses if your model specifies that (a student can attend several courses).
Here is a sample code:
public class Student{
//....
private Course course;
//...
public void attendCourse(Course course){
this.course = course;
}
public Course getCourse(){
return course;
}
}
Now, you can have the following:
Student bob = new Student(...);
Course course = new Course(...);
bob.attendCourse(course);
I assume a Course is not a Student, so inheritance between those classes is probably a bad idea.
You have to declare them public.
A better way is the keep them private, and code a public getter for that variable. for example:
public Award getCourseAward(){
return this.courseAward;
}
Course should not extend Student. If you want to access the courseTitle field of Course, you need to pass a reference to a Course object to the Student and then do course.CourseTitle.
You cannot access private attributes of a class from another, this is one of the main principles of OOP: encapsulation. You have to provide access method to those attribute, you want to publish outside the class. The common approach is setter/getters - getters only, if you want to have your class immutable. Look here: http://en.wikipedia.org/wiki/Mutator_method#Java_example
It does not make sense to arbitrarily extend classes. Student is not a Course or vice versa, so you cannot extend them like that.
What you need to do is:
create a Course first:
Course aCourse = new Course(..);
create a Student:
Student aStudent = new Student(..);
assign the Course to the Student:
aStudent.setCourse(aCourse.title);
Extending Student with Couse because they are not of the same kind. Extending one class with another happens when specializing a more general (in a sense) one.
The solution would be to pass courseTitle as an argument of the Student constructor
There should be 3 separate objects here, a Course, a Student, and an Enrollment. An enrollment connects a Student to a Course, a Course has many Students, and a Student can enroll in many courses. None of them should extend each other.
First,
You are extending Student class in Course class, which means, student class gets all the coruse class properties. So, the student class does not have the courseTitle property.
Second, yes, it is unnesessary - you need to do the following:
public class Course
{
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
}
public class Student
{
private int studentNumber;
private String studentName;
private int studentPhone;
// This is where you keep the course object associated to student
public Course studentCourse;
public Student(int number, String name, int phone, Course course)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = course;
}
}
Example usage would be something like this:
Course course = new Course("ASD", "TITLE", null, "ME", 50, true);
Student student = new Student(1, "JOHN", "5551234", course);
And then, get the course information you need from student via, i.e.:
student.studentCourse.courseTitle;
Since now student.studentCourse will be a course object with all of its properties.
Cheers,
Maybe you do not need to add the course name to student. What I would do is add Students to some datastructure in Course. This is cleaner and reduces the coupling between Course and Student. This would also allow you to have Students being in more than one course. For example:
public class Course extends Student{
private Award courseAward;
private String courseCode;
public String courseTitle;
private Student courseLeader;//change to a student Object
private int courseDuration;
private boolean courseSandwich;
private Set<Student> students;//have course hold a collection of students
/**
* Constructor for objects of class Course
*/
public Course(String code, String title, Award award, Student leader, int duration, boolean sandwich){
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
this.students=new HashSet<Student>();
}
public boolean addStudent(Student student){
return students.add(student);
}
public Set<Student> getStudents(){
return students;
}
}
As mentioned, stay away from the "extends" for this. In general, you shouldn't use it unless the "is-a" relationship makes sense.
You should probably provide getters for the methods on the Course class:
public class Course {
...
public String getTitle() {
return title;
}
}
And then if the Student class needs that, it would somehow get a hold of the course (which is up to you in your design), and call the getter:
public class Student {
private Set<Course> courses = new HashSet<Course>();
public void attendCourse(Course course) {
courses.add(course);
}
public void printCourses(PrintStream stream) {
for (Course course : courses) {
stream.println(course.getTitle());
}
}
}
Here below find out the solution of your problem and if you want to check below code on your machine then create a file named Test.java and paste the below codes:
package com;
class Course
{
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseAward = award;
courseCode = code;
courseTitle = title;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
public Award getCourseAward() {
return courseAward;
}
public void setCourseAward(Award courseAward) {
this.courseAward = courseAward;
}
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getCourseTitle() {
return courseTitle;
}
public void setCourseTitle(String courseTitle) {
this.courseTitle = courseTitle;
}
public String getCourseLeader() {
return courseLeader;
}
public void setCourseLeader(String courseLeader) {
this.courseLeader = courseLeader;
}
public int getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(int courseDuration) {
this.courseDuration = courseDuration;
}
public boolean isCourseSandwich() {
return courseSandwich;
}
public void setCourseSandwich(boolean courseSandwich) {
this.courseSandwich = courseSandwich;
}
}
class Student
{
private int studentNumber;
private String studentName;
private int studentPhone;
private Course studentCourse;
/**
* Constructor for objects of class Student
*/
public Student(int number, String name, int phone, Course course)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = course;
}
public int getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(int studentNumber) {
this.studentNumber = studentNumber;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentPhone() {
return studentPhone;
}
public void setStudentPhone(int studentPhone) {
this.studentPhone = studentPhone;
}
public Course getStudentCourse() {
return studentCourse;
}
public void setStudentCourse(Course studentCourse) {
this.studentCourse = studentCourse;
}
}
class Award{
private long awardId;
private String awardName;
Award(long awardId, String awardName){
this.awardId = awardId;
this.awardName = awardName;
}
public long getAwardId() {
return awardId;
}
public void setAwardId(long awardId) {
this.awardId = awardId;
}
public String getAwardName() {
return awardName;
}
public void setAwardName(String awardName) {
this.awardName = awardName;
}
}
public class Test{
public static void main(String ar[]){
// use your all classes here
}
}

Categories

Resources