set field equal to method's parameter in java - java

So I have code that looks like this:
public class CLASSNAME {
private String name;
private int age;
public METHODNAME(String testName, int testAge) {
//does something
}
public ANOTHERMETHOD() {
//does something else
}
}
I have testName and testAge declared in another class, but I need to access them in my fields so I can use them in other methods. Right now I can only access testAge and testName in the METHODNAME method.
Any help would be much appreciated :)

You should add getters and setters (also called accessors and mutators). For Example,
public class Example {
public Example(String name, int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Then you can modify (or retrieve) the value(s) from an instance of the class.

you can use inheritance here. Parent class have some method. You will extend child class to parent class. And you will get all in child class from parent class.
Parent class need to have getter/setter also.
There is a complete example: Follow this
// A class to display the attributes of the vehicle
class Vehicle {
String color;
private int speed;
private int size;
public int getSize() {
return size;
}
public int getSpeed() {
return speed;
}
public void setSize(int i) {
size = i;
}
public void setSpeed(int i) {
speed = i;
}
}
// A subclass which extends for vehicle
class Car extends Vehicle {
int CC;
int gears;
int color;
void attributescar() {
// Error due to access violation
// System.out.println("Speed of Car : " + speed);
// Error due to access violation
//System.out.println("Size of Car : " + size);
}
}
public class Test {
public static void main(String args[]) {
Car b1 = new Car();
// the subclass can inherit 'color' member of the superclass
b1.color = 500;
b1.setSpeed(200) ;
b1.setSize(22);
b1.CC = 1000;
b1.gears = 5;
// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + b1.color);
System.out.println("Speed of Car : " + b1.getSpeed());
System.out.println("Size of Car : " + b1.getSize());
System.out.println("CC of Car : " + b1.CC);
System.out.println("No of gears of Car : " + b1.gears);
}
}
Resource Link: http://beginnersbook.com/2013/03/inheritance-in-java/

Related

Knowing sub-class type in super-class function

I try to make an algorithm for people at a local register who would like to pay their anual tax for properties. I have an abstract class for Properties, which has essential variables and methods for each other type of property. The problem is, I would like to print for a known Client all the properties and I don't know how to get the type of property through the superclass
I've thought about declaring another variable in the Properties class which would tell me if I have a rang or not, then, knowing this, I would have a Building or a Field. But that doesn't respect the polymorphism property. If I would introduce a new type of property, I would need to change everything.
I am pretty new to java and I have no other clue. Thank you.
public class Client {
private int CNP;
private String Name;
private int totalSum;
private Properties[] properties;
public Client(String Name, Properties[] properties) {
this.Name = Name;
this.properties = properties;
setTotalSum(properties);
CNP = 0;
}
public Client(int CNP, Properties[] properties) {
Name = "No Name Specified";
this.properties = properties;
setTotalSum(properties);
this.CNP = CNP;
}
public Client(String Name, int CNP, Properties[] properties) {
this.Name = Name;
this.properties = properties;
setTotalSum(properties);
this.CNP = CNP;
}
public String toString() {
String s = "Contribuabil: " + getName() + "\n" +
"Proprietati: \n";
for(Properties property:properties) {
s += property.toString();
}
s += "Suma totala: " + getTotalSum();
return s;
}
The Properties class
abstract class Properties {
private String nameAdress;
private int number;
private int paySum;
public Properties(String nameAdress, int number) {
this.nameAdress = nameAdress;
this.number = number;
}
public void setPaySum(int surface) {
paySum = 500 * surface;
}
public void setPaySum(int surface, int rang) {
paySum = (350 * surface) / rang;
}
public int getPaySum() {
return paySum;
}
public String toString() {
//here I would like to print the type of property;
}
The sub-class Building
public class Building extends Properties {
private int surface;
public Building(String nameAdress, int number, int surface) {
super(nameAdress, number);
this.surface = surface;
setPaySum(surface);
}
The sub-class Field
public class Field extends Properties {
private int surface;
private int rang;
public Field(String nameAdress, int number, int surface, int rang) {
super(nameAdress, number);
this.surface = surface;
this.rang = rang;
setPaySum(surface, rang);
}

I keep on getting Cannot find Symbol Error when using Comparable

I keep on getting an error saying Cannot find symbol when trying to compile. The files are both in the same folder, i'm not really sure where i went wrong here.
In this assignment im supposed to write a program that reads a list of employees from a file. The name of the file will be ‘Employee.txt’. The program should output the sorted array to a file called “SortedEmployee.txt”. I already have the Heap class done. Need assistance please.
public class Employee
{
String id;
String name;
String department;
String position;
double salary;
int yos; //Year of Service
//constructor w/ no args
public Employee()
{ salary = 0.0;
id = name = department = position = "";
yos = 0;
}
//constructor w/ args
public Employee(String i, String n, String d, String p, double s, int y)
{
id = i;
name = n;
department = d;
position = p;
salary = s;
yos = y;
}
public void setID(String i)
{ id = i;}
public void setName(String n)
{ name = n;}
public void setDepartment(String d)
{department = d;}
public void setPosition(String p)
{position = p;}
public void setSalary(double s)
{salary =s;}
public void setYOS(int y)
{yos = y;}
public String getID()
{ return id;}
public String getName()
{ return name;}
public String getDepartment()
{return department;}
public String getPosition()
{return position;}
public double getSalary()
{return salary;}
public int getYOS()
{return yos;}
public String toString()
{
String str = "Emplyee Id: " + id + "\nName: " + name +
"\nDepartment: " + department + "\nPosition: " + position
+ "\nSalary: " + salary;
return str;
}
public int compareTo(Employee emp)
{
int idONE = id.compareToIgnoreCase(emp.id);
if (idONE != 0)
return idONE;
return 0;
}
}
public class EmployeeCOMP implements Comparable<Employee>{
#Override
public int compareTo(Employee emp){
return this.id.compareToIgnoreCase(emp.id);
}
}
This is the error I keep on getting.
EmployeeCOMP.java:4: error: cannot find symbol
return this.id.compareToIgnoreCase(emp.id);
^
symbol: variable id
1 error
this refers to the instance of EmployeeCOMP which does not have an id. In this context the compareTo method should be part of the Employee class (not a separate class):
public class Employee {
...
public int compareTo(Employee emp) {
return this.id.compareToIgnoreCase(emp.id); // **this** refers to an Employee instance
}
}
Attempting to use through a separate class suggests you might be needing to implement a Comparator.

Creating an object and calling it

this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)

Project for Java

So my Java teacher wants us to write a program that simply says "Ben Barcomb is 19 years old" That's it, nothing more, nothing less.
Instead of using System.out.println like a normal person he wants us to use an instance variable in the Person class for the full name and age that must be private, he also wants a getter and setter method for the fullname and variable as well. This is the tester code I have, but I'm kind of stuck on the variable and getter/setter methods.
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setFullname("Bilal Gonen");
p1.setAge(76);
String myFullname = p1.getFullname();
int myAge = p1.getAge();
System.out.println(myFullname + " is " + myAge + " years old.");
}
}
public class Person{
private String myFullname;
private int myAge;
public String getFullname()
{
return myFullname;
}
public int getAge()
{
return myAge;
}
public Person(String aFullname)
{
myFullname = aFullname;
}
public void setFullname()
{
myFullname = aFullname;
}
}
Here is an example of a getter and setter. I am sure you can use this as a guide.
public class Person
{
private String firstName;
private String lastName;
public void setName(String f, String l)
{
firstName = f;
lastName = l;
}
public String getFirstName()
{
return firstName;
}
}
Short tutorial on setters and getters.
Not doing your homework for you, but I will provide some help on the getters and setters. Here's an example person class with one variable, add the others you need yourself.
public class Person {
int age;
public void setAge(int age) { // notice how the setter returns void and has an int parameter
this.age = age; // this.age means the age we declared earlier, while age is the age from the parameter
}
public int getAge() { // notice the return type, int? this is because the var we're getting is an int
return age;
}
Thanks to the help of everyone, as well as some of the research I did myself, I got the program to compile and run correctly, here is the source code. Thanks again to everyone who assisted!
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setFullname("Ben Barcomb");
p1.setAge(19);
String myFullname = p1.getFullname();
int myAge = p1.getAge();
System.out.println(myFullname + " is " + myAge + " years old.");
}
}
public class Person
{
private String myFullname;
private int myAge;
public String getFullname()
{
return myFullname;
}
public int getAge()
{
return myAge;
}
public void setAge(int newAge)
{
myAge = newAge;
}
public void setFullname(String aFullname)
{
myFullname = aFullname;
}
}
The valid code is as below, use getters for the String input of System.out.println()
Full test code is as below;
public class PersonTester {
public static void main(String[] args) {
Person p1 = new Person();
p1.setMyFullname("Bilal Gonen");
p1.setMyAge(76);
System.out.println(p1.getMyFullname() + " is " + p1.getMyAge() + " years old.");
}
}
class Person {
private String myFullname;
private int myAge;
public String getMyFullname() {
return myFullname;
}
public void setMyFullname(String myFullname) {
this.myFullname = myFullname;
}
public int getMyAge() {
return myAge;
}
public void setMyAge(int myAge) {
this.myAge = myAge;
}
}
And the output is as below;
Bilal Gonen is 76 years old.
Note: And it will make your job easier whenever a similiar project comes, when making a POJO class (in this example the Person class), use eclipse's (or any IDE's) "generate getters/setters" shortcut (on Eclipse, you can use it with Alt+Shift+S)

Java: What should be done with abstract methods that are only in the superclass in the UML diagram?

I have the below UML diagram:
I've read that abstract methods should be overridden by a subclass. How should I override calculateMonthlyPay() when there is no calculateMonthlyPay() in either subclass? Can I create methods that aren't shown in the UML diagram?
Here is my code for Employee and its subclasses PartTimeEmp and FullTimeEmp for reference.
public abstract class Employee {
Scanner keyboard = new Scanner(System.in);
public String name;
public String ID;
//Employee constructor
public Employee(String name, String ID) {
this.name = name;
this.ID = ID;
}
//ID setter
public void setID(String ID) {
ID = keyboard.nextLine();
this.ID = ID;
}
//name getter
public String getName() {
return name;
}
public abstract String getStatus();
public abstract double calculateMonthlyPay();
#Override
public String toString() {
return "Employee{" + "name=" + name + ", ID=" + ID + '}';
}
}
class PartTimeEmp extends Employee {
public double hourlyRate;
public int hoursPerWeek;
//PartTimeEmp constructor
public PartTimeEmp(String name, String ID){
super(name, ID);
}
public void setHours(int hoursPerWeek) {
this.hoursPerWeek = hoursPerWeek;
}
public void setRate(double hourlyRate) {
this.hourlyRate = hourlyRate;
}
#Override
public String toString() {
return "PartTimeEmp{" + "hourlyRate=" + hourlyRate + ", hoursPerWeek=" + hoursPerWeek + '}';
}
}
class FullTimeEmp extends Employee {
double salary;
//FullTimeEmp constructor
public FullTimeEmp(String name, String ID) {
super(name, ID);
}
//Set salary of employee
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "FullTimeEmp{" + "salary=" + salary + '}';
}
}
The UML diagram shows each method only in the class that first introduced it. Otherwise, each class's UML would show all the methods of all the ancestor classes of its hierarchy, which wouldn't be very convenient.
So you should definitely override calculateMonthlyPay() and getStatus() in the sub-classes, or you wouldn't be able to compile your code.
Since PartTimeEmp instances are instances of Employee, such instances must have all of the methods defined in Employee defined.
Since UML is not used to define these implementation details, the implementation of the methods may be either in Employee or any of its subclasses to which the instance belongs. But it must exist.
if you are implementing a concrete class extending from abstract class, you have to implement all abstract method.
If you can't change the abstract class (modify signature etc), only option left out for you is to implementing if.
class PartTimeEmp extends Employee {
public double hourlyRate;
public int hoursPerWeek;
//PartTimeEmp constructor
public PartTimeEmp(String name, String ID){
super(name, ID);
}
:
:
public double calculateMonthlyPay() {
// do noting
// if you can change the method *calculateMonthlyPay*, you could have thro' some exception here
return 0;
}

Categories

Resources