Add new class variable java + getter/setter method without editing class - java

Is there any way to create new class variable or method in java without editing class java
Example:
I have class Person
public class Person {
private String name;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
and in main class I process like this:
Person personData = new Person();
personData.setName("My Name");
personData.setAddress("Address");
List<Person> person = new ArrayList<Person>();
person.add(personData);
I want to add new person variable in List
and have setNo(); and getNo();
So list index[0] have person with property No, Name, And Address without editing the class Person first.

There is no way in Java to add methods to a class without changing the class source code.
The only possibility you have is to either extend from this class (by creating a subclass that inherits from Person) or to create a completely new class that contains a Person object.
The first concept is called inheritance; the second one composition. You can find a discussion of "one versus the other" here for example.
But in essence the answer: step back and read a good book about Java.

I would probably create another class which extends Person.
import java.util.ArrayList;
import java.util.List;
public class PersonNo extends Person {
public static void main(String[] args) {
PersonNo personData = new PersonNo();
personData.setName("My Name");
personData.setAddress("Address");
List<PersonNo> person = new ArrayList<>();
person.add(personData);
}
public void setNo(int n) {
this.no = n;
}
public int getNo() {
return this.no;
}
private int no;
}
This requires you to change the List type to "PersonNo" and to add "PersonNo"s, but it will give you the functionality you need. If you create the List with "Person", you can add "PersonNo"s but you will not have the setNo/getNo unless you cast the "Person" into a (PersonNo).

Related

How to return a class using the constructor in java?

How to return this Customer class so i can use this class in another class.
If i use static instead of void then i am unable to call customer Transaction from the constructor.
I tried writing new keyword but it did not work but this is returning a class:
import java.util.ArrayList;
public class Customer {
private String name;
private ArrayList<Double> customerTranscation;
public Customer(String name) {
this.name = name;
this.customerTranscation = new ArrayList<Double>();
}
public String getName() {
return name;
}
public ArrayList<Double> getCustomerTranscation() {
return customerTranscation;
}
public void newCustomerTran(String name,double amount){
this.customerTranscation.add(amount);
this.name = name;
}
}
How can I return Customer class so I can use this in another class?
In you second class, You got to create the object of the customer class first .
Like Customer c=new Customer(“abc”);
This is going to initialise the CustomerTransaction List.
Then call c.newCustomerTrans(“name”).which will invoke the newCustomeTrans method from your second class.
If you want an customer object to be returned . Do .!
public Customer newCustomerTrans(String name ,double amount){
//create a new object p of Customer using new
//set name to p
//initialise and set customer trans arraylist to p
// return p
}
This way you can use Customer class details from your second class..

Make a new instance of an unknown subclass using superclass object in java

Here I have an abstract class Person and multiple subclasses:
public abstract class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
public class ComputerScientist extends Person {
public String job;
public ComputerScientist(String name, String job) {
super(name);
this.job = job;
}
}
public class SoftwareEngineer extends Person {
public String job;
public SoftwareEngineer(String name, String job) {
super(name);
this.job = null;
}
}
This is what I run:
public static void main(String[] args) {
List<Person> people = new ArrayList<Person>();
person.add(new ComputerScientist("ben", "job"));
person.add(new SoftwareEngineer("larry", "job"));
Random r = new Random();
Person person = people.get(r.nextInt(people.size() - 1);
}
Person becomes the same as the Person in the list, how do I get it as a person clone. Cloning and new Instance do not work.
I can probably do it using a copy method (requres me to rewrite a great deal of code) but is there any (perhaps more efficient) way to do it without?
You can create a method to create a new Object of the Person(as per the sub class) and another method to copy the states in the new object. Refer below approach for the basic implementation of the same.
public abstract class Person{
...//your states and methods
protected void copy(Person copiedPerson){
copiedPerson.name = this.name;
}
public abstract Person getCopyPerson();
}
public class SoftwareEngineer extends Person{
....//your states and methods
#override
protected void copy( Person copiedPerson ){
super(copiedPerson);
copiedPerson.job = this.job;
}
#override
public Person getCopyPerson(){
Person copyPerson = new SoftwareEngineer();
copy(copyPerson);
return copyPerson;
}
}
Now whenever you fetch the object of Person, simply call getCopyPerson() on it to get a copy object.
I'm not a fan of clone() - see also Clone() vs Copy constructor- which is recommended in java
So, instead use a copy constructor or copy method, that accepts a person and then transfers the relevant information
Make your class cloneable with implements with Cloneable interface. and at object user .clone() method to clone of person class object

How do I use Java getters and setters with a collection of data without explicitly typing out the attributes for each item?

I am very new to Java and to programming in general, and I have an assessment to complete where I load employees (with name, age, and department attributes; department can be only one of four enumerated values) into a program that will sort them by age and tell if the age is a prime number. The assignment requires Company, Department, and Employee classes. I am confident that I can figure out age/prime components — I know how to google for algorithms. What I am struggling with is putting all the discrete pieces into a cohesive whole.
Here is what I have so far. I've put in one employee, but the way I'm doing it seems completely inelegant and inefficient. I am sure there is a better way, but I've hit a mental block.
EDIT: as was pointed out below, I was unclear. What I am asking help with is populating the data structure.
Company class:
public class Company {
static Employee one = new Employee();
public static void main(String[] args) {
one.setName("Counting Guru");
one.setAge(55);
one.setDepartment(DepartmentList.ACCOUNTING);
}
}
DepartmentList class:
import java.util.EnumMap;
import java.util.Map;
import java.util.Set;
public enum DepartmentList {
ACCOUNTING, MARKETING, HUMANRESOURCES, INFORMATIONSYSTEMS;
public static void main(String[] args) {
Map<DepartmentList,String>
enumMap=new EnumMap<DepartmentList,String>(DepartmentList.class);
enumMap.put(DepartmentList.ACCOUNTING, "Accounting");
enumMap.put(DepartmentList.MARKETING, "Marketing");
enumMap.put(DepartmentList.HUMANRESOURCES, "Human Resources");
enumMap.put(DepartmentList.INFORMATIONSYSTEMS, "Information Systems");
Set<DepartmentList> keySet = enumMap.keySet();
for (DepartmentList department : keySet) {
String value = enumMap.get(department);
System.out.println("ENUMMAP VALUE:"+value);
}
}
}
Employee class:
public class Employee {
String empName;
int empAge;
DepartmentList empDept;
Employee() {
}
public String getName() {
return empName;
}
public void setName(String name) {
this.empName = name;
}
public int getAge() {
return empAge;
}
public void setAge(int age) {
this.empAge = age;
}
public DepartmentList getDepartment() {
return empDept;
}
public void setDepartment(DepartmentList department) {
this.empDept = department;
}
public Employee(String empName, int empAge, DepartmentList empDept){
}
}
I also have a Department class, but it's currently empty.
Am I on the right track? Can someone give me a nudge? Thank you!
Don't hard-code the data inside the Java program. Put the data in a file and write methods to load the data.
If you MUST hardcode the data in the program, use something like this sample:
public class Employee
{
String name;
int age;
public Employee(String name, int age)
{
this.name = name;
this.age = age;
}
// getters, setters, etc.
}
In the main program
private static Employee[] empData =
{
new Employee("John Smith", 50),
new Employee("Fred Jones", 25),
.
.
.
};
Now you have a static array of Employee objects that you can "load" into your data structure.
If you're asking if there is something like a property in Java, no, there isn't (at least not yet).
If you're asking how to populate your objects something like an IOC container, like Spring, would be a better choice.
Now as it comes to your code you have two main methods in two different classes. Only one will be called. If you want to create a static instance you will be better do
static Employee one = new Employee("Counting Guru", 55, DepartmentList.ACCOUNTING);
or
static Employee one = new Employee();
static {
one.setName("Counting Guru");
one.setAge(55);
one.setDepartment(DepartmentList.ACCOUNTING);
}
When it comes to the enum then you'll better define a constructor for it
public enum DepartmentList {
ACCOUNTING("Accounting"), MARKETING("Marketing");
private String displayName;
public DepartmentList(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return diplayName;
}
}
In the Employee constructor you need to assign the field values to the ones received as arguments.

String Array object in Java

I am trying to print the first element on the two arrays in my Athlete class, country and name. I also need to create a object that simulates three dive attemps an athlete had (that is initially set to zero). I am new to OOP and I dont know how to go abouts doing this in my main... as far as constructors go. This is what i have done so far...
this is the main:
import java.util.Random;
import java.util.List;
public class Assignment1 {
public static void main(String[] args) {
Athlete art = new Athlete(name[0], country[0], performance[0]);
}
}
I just really am not sure what to do...
And this is the class with the arrays.
import java.util.Random;
import java.util.List;
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
//Here i would like to create something that would be representing 3 dive attemps (that relate to dive and score. eventually.)
Athlete(String[] name, String[] country, Performance[] performance) {
this.name = name;
this.country=country;
this.performance=performance;
}
public Performance Perform(Dive dive){
dive.getDiveName();
return null;
}
public String[] getName() {
return name;
}
public void setName(String[] name) {
this.name = name;
}
public String[] getCountry() {
return country;
}
public void setCountry(String[] country) {
this.country = country;
}
}
thanks in advance for any help and input!
btw there is other classes too, just not relevant atm..
First, as for your Athlete class, you can remove your Getter and Setter methods since you have declared your instance variables with an access modifier of public. You can access the variables via <ClassName>.<variableName>.
However, if you really want to use that Getter and Setter, change the public modifier to private instead.
Second, for the constructor, you're trying to do a simple technique called shadowing. Shadowing is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing:
----------Shadowing sample----------
You have the following class:
public String name;
public Person(String name){
this.name = name; // This is Shadowing
}
In your main method for example, you instantiate the Person class as follow:
Person person = new Person("theolc");
Variable name will be equal to "theolc".
----------End of shadowing----------
Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter. Remove your parameters on your constructor.
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};
public Athlete() {
}
In your main method, you could do this.
public static void main(String[] args) {
Athlete art = new Athlete();
System.out.println(art.name[0]);
System.out.println(art.country[0]);
}
}
Currently you can't access the arrays named name and country, because they are member variables of your Athelete class.
Based on what it looks like you're trying to do, this will not work.
These arrays belong in your main class.
Your attempt at an athlete class seems to be dealing with a group of athletes, which is a design fault.
Define a class to represent a single athlete, with fields that represent the athlete's attributes:
public class Athlete {
private final String name;
private final String country;
private List<Performance> performances = new ArrayList<Performance>();
// other fields as required
public Athlete (String name, String country) {
this.name = name;
this.country = country;
}
// getters omitted
public List<Performance> getPerformances() {
return performances;
}
public Performance perform(Dive dive) {
// not sure what your intention is here, but something like this:
Performance p = new Performance(dive, this);
// add new performance to list
performances.add(p);
return p;
}
}
Then your main method would use ti like this:
public class Assignment1 {
public static void main(String[] args) {
String[] name = {"Art", "Dan", "Jen"};
String[] country = {"Canada", "Germant", "USA"};
Dive[] dive = new Dive[]{new Dive("somersault"), new Dive("foo"), new Dive("bar")};
for (int i = 0; i < name.length; i++) {
Athlete athlete = new Athlete(name[i], country[i]);
Performance performance = athlete.perform(dive[i]);
// do something with athlete and/or performance
}
}
}
I think you are a little messed up with what you doing.
Athlete is an object, athlete has a name, i has a city where he lives.
Athlete can dive.
public class Athlete {
private String name;
private String city;
public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){}
}
public class Main{
public static void main (String [] args){
String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord
--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);
}
}
public static void main(String[] args) {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
// initialize your performance array here too.
//Your constructor takes arrays as an argument so you need to be sure to pass in the arrays and not just objects.
Athlete art = new Athlete(name, country, performance);
}
First off, the arrays are pointless, let's get rid of them: all they are doing is providing values for mock data. How you construct mock objects has been debated ad nauseum, but clearly, the code to create the fake Athletes should be inside of a unit test. I would use Joshua Bloch's static builder for the Athlete class, but you only have two attributes right now, so just pass those in a Constructor. Would look like this:
class Athlete {
private String name;
private String country;
private List<Dive> dives;
public Athlete(String name, String country){
this.name = name;
this.country = country;
}
public String getName(){
return this.name;
}
public String getCountry(){
return this.country;
}
public String getDives(){
return this.dives;
}
public void addDive(Dive dive){
this.dives.add(dive);
}
}
Then for the Dive class:
class Dive {
private Athlete athlete;
private Date date;
private double score;
public Dive(Athlete athlete, double score){
this.athlete = athlete;
this.score = score;
this.date = new Date();
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
public Athlete getAthlete(){
return this.athlete;
}
}
Then make a unit test and just construct the classes, and manipulate them, make sure that they are working. Right now they don't do anything so all you could do is assert that they are retaining the Dives that you are putting in them. Example:
#Test
public void testThatDivesRetainInformation(){
Athlete art = new Athlete("Art", "Canada");
Dive art1 = new Dive(art, 8.5);
Dive art2 = new Dive(art, 8.0);
Dive art3 = new Dive(art, 8.8);
Dive art4 = new Dive(art, 9.2);
assertThat(art.getDives().size(), is(5));
}
Then you could go through and add tests for things like, making sure that you can't construct a dive without an athlete, etc.
You could move construction of the athletes into the setup method of the test so you could use it all over the place. Most IDEs have support for doing that with a refactoring.

Calling a non-static method in a seperate class to a main program

I have a Java program where I have a main class and another class called Person (that makes a 'person' class) with 2 methods. The methods are non-static and are called getName and getAge that stores this info a person element of an ArrayList.
How do I call these in the main program? I know I have to declare an instance of the class but I'm still not sure how to actually do it.
Considering Person a Class with 2 methods:
public class Person{
private String mName;
private int mAge;
public Person(String name, String age){
this.mName = name;
this.mAge = age;
}
//If you want this class to be Immutable please remove the setter methods()//
public void setName(String name){
this.mName = name;
}
public void setAge(String age){
this.mAge = age;
}
public String getName(){
return this.mName ;
}
public String getAge(){
return this.mAge ;
}
}
The Class containing main() method:
public class TestMain{
public static ArrayList<Person> aList = new ArrayList<Person>();
public static void main(String[] args){
Person person1 = new Person("Vivek",26);
Person person2 = new Person("Vicky",27);
aList.add(person1);
aList.add(person2);
}
}
In your main code you can do something like:
Person p = new Person();
p.setName("Jericho Jones");
p.setAge(153);
Of course, it's impossible to tell exactly without seeing the Person class.
You need to instantiate an object for this class.
Person p = new Person();
p.getName()....

Categories