How to call a method in another class in Java? - java

Currently I have two classes. a classroom class and a School class. I would like to write a method in the School class to call public void setTeacherName(String newTeacherName) from the classroom class.
classroom.java
public class classroom {
private String classRoomName;
private String teacherName;
public void setClassRoomName(String newClassRoomName) {
classRoomName = newClassRoomName;
}
public String returnClassRoomName() {
return classRoomName;
}
public void setTeacherName(String newTeacherName) {
teacherName = newTeacherName;
}
public String returnTeacherName() {
return teacherName;
}
}
School.java
import java.util.ArrayList;
public class School {
private ArrayList<classroom> classrooms;
private String classRoomName;
private String teacherName;
public School() {
classrooms = new ArrayList<classroom>();
}
public void addClassRoom(classroom newClassRoom, String theClassRoomName) {
classrooms.add(newClassRoom);
classRoomName = theClassRoomName;
}
// how to write a method to add a teacher to the classroom by using the
// classroom parameter
// and the teachers name
}

You should capitalize names of your classes. After doing that do this in your school class,
Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);
Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters

Try this :
public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
myClassRoom.setTeacherName(TeacherName);
}

class A{
public void methodA(){
new B().methodB();
//or
B.methodB1();
}
}
class B{
//instance method
public void methodB(){
}
//static method
public static void methodB1(){
}
}

in School,
public void addTeacherName(classroom classroom, String teacherName) {
classroom.setTeacherName(teacherName);
}
BTW, use Pascal Case for class names. Also, I would suggest a Map<String, classroom> to map a classroom name to a classroom.
Then, if you use my suggestion, this would work
public void addTeacherName(String className, String teacherName) {
classrooms.get(className).setTeacherName(teacherName);
}

Instead of using this in your current class setClassRoomName("aClassName"); you have to use classroom.setClassRoomName("aClassName");
You have to add the class' and at a point like
yourClassNameWhereTheMethodIs.theMethodsName();
I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.

Related

Java factory but objects have slightly differrent attributes

I want to program a factory that creates two types of People which are "Employee" and "Entrepreneur". They both share the same basic "Person" attributes but they also implements their unique ones.
The problem is that if i want to return a method or an attribute that is not declared in the "Person" abstract class the program doesn't find it (since obviously I'm generating an object that is type "Person" and not specifically "Employee" or "Entrepreneur" ).
How do i tackle this problem?
This is the Demo class
public class Demo{
public static void main(String[] args){
PersonFactory pf = new PersonFactory();
Person p1 = pf.getPerson("Employee");
p1.presentation();
System.out.println(p1.getComplanyName());
}
}
This is the abstract class
public abstract class Person{
String name;
String surname;
abstract void presentation();
}
Those are the two concrete classes that extend Person
public class Entre extends Person{
int licenseNumber;
#Override
public void presentation(){
System.out.println("hi i'm an Entrepreneur");
}
public int licenseNumber(){
return licenseNumber;
}
}
public class Empl extends Person{
String companyName;
#Override
public void presentation(){
System.out.println("hi i'm an employee");
}
public String getCompanyName(){
return companyName;
}
}
Finally the Factory
public class PersonFactory{
public Person getPerson(String type){
if(type.equalsIgnoreCase("ENTREPRENEUR")){
return new Entre();
}
else if(type.equalsIgnoreCase("Employee")){
return new Empl();
}
return null;
}
}

Java: Calling a parent's method with child's member variable

Let's say I have an abstract parent class that has member variables which are used in a method.
public abstract class Person{
public String jobTitle;
public void printJob(){
System.out.println(jobTitle);
}
}
If I now have two child classes
public class Teacher extends Person{
public String jobTitle = "Teacher";
}
public class Janitor extends Person{
public String jobTitle = "Janitor";
}
and I want to avoid code cloning, i.e. implementing the same printJob()-method in both classes, I now have a problem, since the printJob()-method is unable to access member variables of the child classes.
Is there any way that i can call a parent classes' method but have the method use the child classes' member variables?
You can use abstract methods like this
public abstract class Person {
public void printJob() {
System.out.println(getJobTitle());
}
protected abstract String getJobTitle();
public static void main(String[] args) {
Person teacher = new Teacher();
Person janitor = new Janitor();
System.out.println(teacher.getJobTitle());
System.out.println(janitor.getJobTitle());
}
}
class Teacher extends Person {
#Override
protected String getJobTitle() {
return "Teacher";
}
}
class Janitor extends Person {
#Override
protected String getJobTitle() {
return "Janitor";
}
}
Updated after op's comment for code cloning...
public class Person {
public static void main(String[] args) {
System.out.println(new Teacher().job);
System.out.println(new Janitor().job);
}
private static class Teacher extends Person {
private String job = "Teacher";
}
private static class Janitor extends Person {
private String job = "Janitor";
}
}

java - sending variables through nested classes

I have a class that has a variable of type Name.
public class Holder {
private Name name;
private int snumber;
The Name class has two strings called first and last that are assigned values by setter methods. I would like to send over the strings from the Name class to name in the Holder class, but I'm having trouble doing so. I think I've taken a step in the right direction by doing this
public class Holder {
private Name name;
private int snumber;
public void setName(){
name = new Name();
name.getFirst();
name.getLast();
}
but I can't say that I really know what the correct approach is. I also tried name.setFirst(getFirst) but that doesn't work. Any ideas would be appreciated.
The same way you would if the class wasn't nested.
Your setName() method should take a parameter (maybe 2, first and last) and then invoke the name.setFirstName(), name.setLastName() methods.
Right now, your setName() method isn't doing anything.
E.G:
public class Holder
{
private Name name;
private int snumber;
public Holder()
{
this.name = new Name();
}
public void setName(String firstName, String lastName)
{
this.name.setFirst(firstName);
this.name.setLAst(lastName);
}
}
Here is a good article explaining the relationship between Java inner and outer classes:
https://www.tutorialspoint.com/java/java_innerclasses.htm
class Outer_Demo {
// private variable of the outer class
private int num = 175;
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2 {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Instantiating the inner class
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}
Note that the example creates instances of both "Outer_Demo" AND "Inner_Demo (outer.new Inner_Demo();).
Ok, so I figured something out that works.
public class Holder {
private int snumber;
private Name name;
public void setName(Name n){
name=n;
}
public Name getName(){
return name;
}

UML class diagram implementation Address-Addressbook

I have 2 class diagrams, class Address
+forename
+surename
+street
+houseno
+code
+state
+toString
second Addressbook
insert(address: Address)
toString()
searchSurename (surename: string): Address[*]
+searchForename(forename: string): Address[*]
i implemented address:
public class Address {
public static String forename;
public static String surename;
public static String street;
public static int houseno;
public static int code;
public static String state;
public String toString(){
return this.forename + this.surename + this.street + this.houseno + this.code + this.state;
}
How can I implement Addressbook as easy as possible?
EDIT:
public class addressbook{
private static ArrayList<Address> book;
public addressbook(){
book = new ArrayList<Address>();
}
}
EDIT QUESTION:
Am I allowed to add new methods or attributes in a implementation outside the ones that we use in our class diagrams?
EDIT 2:
First try implementing method searchSurename with an ArrayList:
public static String searchSurename(String surename){
boolean exist = false;
if(this.addresses.isEmpty()){
return null;
}
for(int i=0;i<this.addresses.size();i++) {
if(this.addresses.get(i).getSurename() == surename) {
exist=true;
break;
}
if(exist) {
return this.addresses.get(surename);
} else {
return this.addresses.get(surename);
}
}
// return ?!?
}
The Program give me Errors at "this" at any line, maybe a mistake but I cant tell! It Looks a Little bit too difficult, I don't find any implementations where searching through a list is simple.
You could implement it in a way like this. Look at the api for arrayList for using its methods.
public class Adressbook {
List<Adress> adresses = new ArrayList<Adress>();
public Adressbook(){
adresses = new arraylist<Adress>();
}
public insert (Adress adress){
adresses.add(adress)
}
public searchSurename(String Surename){
}
public searchForename(String forename){
}
public String toString(){
}
ArrayList api:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
To have unique address use set collection interface
public class Adressbook {
....
private Set<Adress> adresses = null;
public Adressbook(){
adresses = new HashSet<Adress>();
}
public void add(Adress adress){
adresses.add(adress)
}
...
}

Searching in an Arraylist

Currently I have two classes. A Classroom class and a School class. I would like to write a method in the School class public void showClassRoomDetails which would find the classroom details by only using the teacherName.
e.g.
teacherName = Daniel className = Science
teacherName = Bob className = Maths
so when I input Bob, it would print out Bob and Maths
many, thanks
public class Classroom
{
private String classRoomName;
private String teacherName;
public void setClassRoomName(String newClassRoomName)
{
classRoomName = newClassRoomName;
}
public String returnClassRoomName()
{
return classRoomName;
}
public void setTeacherName(String newTeacherName)
{
teacherName = newTeacherName;
}
public String returnTeacherName()
{
return teacherName;
}
}
import java.util.ArrayList;
public class School
{
private ArrayList<Classroom> classrooms;
private String classRoomName;
private String teacherName;
public School()
{
classrooms = new ArrayList<Classroom>();
}
public void addClassRoom(Classroom newClassRoom, String theClassRoomName)
{
classrooms.add(newClassRoom);
classRoomName = theClassRoomName;
}
public void addTeacherToClassRoom(int classroomId, String TeacherName)
{
if (classroomId < classrooms.size() ) {
classrooms.get(classroomId).setTeacherName(TeacherName);
}
}
public void showClassRoomDetails
{
//loop
System.out.println(returnClassRoomName);
System.out.println(returnTeacherName);
}
}
Do you really need a list here ?
A Map holding classroom - teacher associations would be more helpful for what you're trying to achieve.
But there are also strange things in your code: for instance, why do you hold a classRoomName and teacherName as instance variables in your School class ?
Change your method signature to take a targetTeacherName as a parameter. Loop through the classrooms until you find one with that teacher. Output the information of that classroom.
Since you are using an ArrayList you could simply use a for each statement:
public void showClassRoomDetails(String teacherName)
{
for (Classroom classroom : this.classrooms)
{
if (classroom.returnTeacherName().equals(teacherName))
{
System.out.println(classroom.returnClassRoomName());
System.out.println(classroom.returnTeacherName());
break;
}
}
}
As a small suggestion, do not name your methods returnXxx(), use getXxx() instead, it is the standard Javabean convention.

Categories