Java Object Oriented - Advanced Constructors Assistance ? :\ - java

Can someone please check my code and determine why my pickup function's not working.
-- write missing methods for these procedures to occur
Dog bob = new Dog(5);
System.out.println(bob);
bob.walk();
bob.walk();
bob.pickUp("Tennis ball");
System.out.println(bob);
bob.drop();
bob.bark();
System.out.println(bob);
-- In my class where I've defined the pickUp method:
public Head()
{
}
public void pickUp(String object)
{
this.object = object;
System.out.println("Picked up "+object);
}
public String getObject()
{
return object;
}
public void drop()
{
System.out.println("Dropped "+object);
object = null;
}
public void bark()
{
System.out.println("WOOF!");
}
public String toString()
{
return "Head is holding "+ object;
}
}
-- The other class where I'm utilising the method:
public class Dog
{
private int position;
private Leg hind1;
private Leg hind2;
private Leg front1;
private Leg front2;
private Head head = new Head();
//Constructor for Dog class
public Dog(int position)
{
hind1 = new Leg(position-2);
hind2 = new Leg(position-2);
front1 = new Leg(position+2);
front2 = new Leg(position+2);
}
public void walk()
{
front1.step();
front2.step();
hind1.step();
hind2.step();
System.out.println("Pitter patter...");
}
public String toString()
{
return "Head is holding " + head+", Leg at "+hind1.position+", Leg at "+ hind2.position+", Leg at "+front1.position+", Leg at "+front2.position;
}
public void pickup()
{
head.pickUp(head.object);
}
public void drop()
{
head.drop();
}
public void bark()
{
head.bark();
}
PS. head is a new object I've made which belongs to the Head Class, Which is where the first code is from. I'm currently trying to get the second code working to display a picked up object that head picked up.
-EDIT : Even if I do put a string in(Eg. head.pickUp("ball");), it still displays "cannot find symbol - method.pickUp(java.lang.String)" when I try running the procedures.

EDITED (a third time!): Now that you've posted your code, I've confirmed that my answer below is correct. Tl;dr - you're trying to use head.object before it's been set. What you should be passing in to pickUp is a string that represents the name of the object you want to pick up. For example, head.pickUp("ball");
It would help if you could clarify a bit more what you mean by "not working" - however, it looks like you've got a sort of chicken-and-egg problem here:
If I'm reading this right, your code looks something like this? (Including the entire class in your comment might help)
public class Head {
String object;
public void pickUp(String object)
{
this.object = object;
System.out.println("Picked up "+object);
}
}
public class SomeOtherClass {
Head head = new Head();
public void pickup()
{
head.pickUp(head.object);
}
}
EDITED (again) for clarity - It looks like you're trying to use the pickup function (the one in SomeOtherClass) to define the object property of your head. However, by calling it with head.object, you assume that head.object is already defined. Where are you actually setting the string you want to use?
It's not really clear what you're trying to accomplish here - but you might want to try either 1) setting head.object in a constructor in your head class. or 2) calling head.pickUp with a string other than head.object (which hasn't been set yet). - Try replacing head.object with "Hello World", for starters. Or, if I've totally misunderstood your intent, perhaps give us a bit more context?
EDITED - because I realized that your pickup function wasn't in Head.

Related

Getting Variables From Java constructor

I'm new to Java programming, sorry if this is a dumb question.
I find it hard to word this question properly, but I have an assignment to create a aircraft class that can make aircraft land, takeoff etc. And need to test it using Testclass. When the new object are entered it automatically assigns a unique ID to the aircraft in the constructor.
I can do this using a instance method fine as it has a return value which is returned to to Testclass. The question wants me to do this in the constructor itself, however, the constructor never returns anything. So the variable never gets sent to the Testclass. I clearly am not understanding OOP properly. Even when I try to just use a getter method to get the ID created in the constructor it gives me the initialized variable before the the constructor has worked on this. This is the code I have so far and its completely wrong I know but if someone could point me in the right direction or tell me how to word this question better it would be a massive help.
// I need to enter 3 aircraft into the system in the testclass
public class Aircraft {
private int aircraftID;
private static int lastID;
private String airportcode;
private int ID = 100;
private int count;
public Aircraft(int a, int b, int c){
// Constructor
// Assign ID
this.ID = a;
lastID = ID;
ID++;
this.ID =b;
lastID = ID;
ID++;
}
}
OK, you want to create an Aircraft that has an automatically-assigned unique identifier, and can take off and land. That implies you need a field for tracking the identifier, a field for tracking whether it's in the air (or not), and methods for the take off and land operations. You also need a static field for generating the unique identifiers. (Note that this implementation isn't thread safe.)
private class Aircraft {
private static int staticId = 0;
private int uniqueId = 0;
private boolean onGround = true; // Aircraft start on the ground in this implementation
public Aircraft(){
this.uniqueId = staticId; // putting this line first makes uniqueId zero-indexed in effect
staticId++;
}
public void land(){
onGround = true;
}
public void takeoff(){
onGround = false;
}
public boolean isFlying(){
return !onGround; // If it's not on the ground, it's flying
}
public int getUniqueId(){
return uniqueId;
}
}
Unit tests checks all of the methods and expected functionality of the class in question:
import org.junit.Test;
import static org.junit.Assert.*;
import Aircraft;
class Testclass {
private final Aircraft aircraft = new Aircraft();
#Test
public void hasId(){
aircraft.getUniqueId() >= 0;
}
#Test
public void canLand(){
assertTrue(aircraft.land());
}
#Test
public void canTakeOff(){
assertTrue(aircraft.takeOff());
}
#Test
public void checkFlightOperationsAreTrackedCorrectly(){
aircraft.land();
assertFalse(aircraft.isFlying());
aircraft.takeOff();
assertTrue(aircraft.isFlying());
}
}
As pointed out a constructor does not return anything (the simplified version is that with new it returns an object instance). I am kinda guessing at what you are trying to acomplish, but I'll have a go anyways. It seems to me that you are trying to cram the construction of 3 objects into one constructor - which is why your constructor has 3 parameters. Also you are playing havoc with the IDs.
I have removed all the variables that I didnt quite understand, leaving only ID that increments with each instantiated Aircraft. The #Override is mainly just for show.
public class Aircraft {
private int aircraftID;
private static int lastID = 0;
#Override
public String toString(){
return "Aircraft_" + this.aircraftID;
}
public Aircraft() {
lastID++;
this.aircraftID = lastID;
}
}
I took the liberty and wrote the TestClass just to see if we have the same thing in mind. Again the printAircraft() method is for show.
public class TestClass {
private List<Aircraft> aircrafts;
public TestClass(){
aircrafts = new ArrayList<>();
}
public void addAircraft(Aircraft a){
aircrafts.add(a);
}
public void printAircraft(){
Iterator<Aircraft> it = aircrafts.iterator();
while(it.hasNext()){
System.out.println(it.next().toString());
}
}
}
and to test it, we create and instance of TestClass add 3 Aircraft instances and print out the contents
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.printAircraft();
}
This would be the case if you are to write the TestClass. If that is given, it would help to know what it looks like - maybe that would help us understand better.

Conflict of method call using Interface in Java

Yesterday, I had an interview and I was given the following scenario:
There are 3 classes namely Main.java, MobilePhone.java, DeskPhone.java and one Interface ITelephone.java. powerOn() method is implemented in both classes MobilePhone.java and DeskPhone.java.
How can I call powerOn() method in DeskPhone class after creating an instance of MobilePhone class? In other word, how can I print "You are in DeskPhone class" and "You are in MobilePhone class" in last two calls in Main class?
Is there any another way to solve this problem without renaming powerOn() method in either of class?
Main.java
public class Main {
public static void main(String[] args) {
ITelephone timsPhone;
timsPhone = new DeskPhone(123456);
timsPhone.powerOn();
timsPhone = new MobilePhone(45678);
//Question begins here
timsPhone.powerOn();
timsPhone.powerOn();
}
}
ITelephone.java
public interface ITelephone {
void powerOn();
}
MobilePhone.java
public class MobilePhone implements ITelephone{
private int myNumber;
public MobilePhone(int myNumber) {
this.myNumber = myNumber;
}
#Override
public void powerOn() {
System.out.println("You are in MobilePhone class");
}
}
DeskPhone.java
public class DeskPhone implements ITelephone {
private int myNumber;
public DeskPhone(int myNumber) {
this.myNumber = myNumber;
}
#Override
public void powerOn() {
System.out.println("You are in DeskPhone class");
}
}
Assign the MobilePhone object to a different local variable.
In the current code, once the value of the timsPhone variable is replaced by the MobilePhone object, the DeskPhone object is unreachable and you cannot call its powerOn() method.
Suggested code:
ITelephone timsDeskPhone = new DeskPhone(123456);
timsDeskPhone.powerOn();
ITelephone timsMobilePhone = new MobilePhone(45678);
timsMobilePhone.powerOn();
timsDeskPhone.powerOn();
Output
You are in DeskPhone class
You are in MobilePhone class
You are in DeskPhone class
You might try to isolate in a static method the calling to your interface method..
public class Main {
public static void main(String[] args) {
phonePowerOn(new DeskPhone(123456));
phonePowerOn(new MobilePhone(45678));
}
static void phonePowerOn(ITelephone timsPhone){
if (timsPhone != null){
timsPhone.powerOn();
}
}
}
Either you misunderstood the question, it was a trick, or possibly a little of both. Were those first four lines of main given to you like that? Did they tell you that you can't change them? Then the tactful response might be adding a few lines strategically like this:
static void main(String[] args){
ITelephone timsPhone;
timsPhone = new DeskPhone(123456);
timsPhone.powerOn();
ITelephone timsDeskPhone = timsPhone;
timsPhone = new MobilePhone(45678);
ITelephone timsMobilePhone = timsPhone;
timsPhone = timsDeskPhone;
timsPhone.powerOn();
timsPhone = timsMobilePhone;
timsPhone.powerOn();
}
This meets their specifications and shows an understanding of interfaces and references. With a question like this, the code is only of secondary importance. I would think they're really trying to assess communication, response to stress, and maybe even creativity. So just immediately saying, "You can't do that" really isn't much better than one that throws a ClassCastException.
The fun way is to fight fire with fire:
public class MobilePhone implements ITelephone{
private int myNumber;
public MobilePhone(int myNumber) {
this.myNumber = myNumber;
}
private int powerOnCallCount = 0;
#Override
public void powerOn() {
if (powerOnCallCount == 0){
System.out.println("You are in DeskPhone class")
} else {
System.out.println("You are in MobilePhone class");
}
powerOnCallCount++;
}
}
Again, we've only added code, it meets their specifications, and shows the same understanding of interfaces and references.
Or course, a sarcastic answer like this usually won't win points with the interview panel, but has use in the right situation. Remember, they're on trial, too. If I've already tried to gently steer towards a solution like the first and they don't back down, now I'm getting suspicious of their technical knowledge and company culture. If I've noticed a few other yellow flags, then I'd consider something like this to turn the tables. The kind of company I'd want to work for would appreciate that I already tried the tactful approach, met their specifications without compromising technical knowledge, and had enough spine to try my own test on them. I'd probably only resort to it if I was already convinced I didn't want the job, but wanted to give them one last chance to win me over.
Plus, if they practice test driven design, they'd pretty much have to offer me the job right on the spot.

How do I get the dynamic class name of an object?

So I have a List of Actors and I want to get each Actors dynamic class name.
For example here is my Actor list: People, Birds, Cows.
I want to get as result the same: "People, Birds, Cows" but without a name attribute in the Actors class. Is it possible?
Example code (here instead of list I used array) :
public Area map[][];
map[0][0] = new AntHillArea();
String name = map[0][0].getClass().getName(); //this results "Area" instead of AntHillArea
Edit: There was other problems with the code, getClass().getName() works fine. Thanks anyway.
String className = obj.getClass().getSimpleName();
Update:
public class Test {
public static void main(String[] args) {
Area map[][] = new Area[1][1];
map[0][0] = new AntHillArea();
String name = map[0][0].getClass().getSimpleName(); // returns "AntHillArea"
System.out.println(name);
}
}
class Area {
}
class AntHillArea extends Area {
}
Use getSimpleName method. It gives you only class and will remove any package if having.
You can do this:
class Dog
{
//code
public String getName()
{
return Dog.class.getName();
}
//better
#Override
public String toString()
{
return Dog.class.getName();
}
}
And similarly for each class. Or have a global one as mentioned in other answers as:
public static String getClassName(Class<?> clas){
return clas.getName();
}
To use Dog dog = new Dog(); getClassName(dog.class);

Java-How do I call a class with a string?

I am a beginner programmer and this is my first question on this forum.
I am writing a simple text adventure game using BlueJ as a compiler, and I am on a Mac. The problem I ran into is that I would like to make my code more self automated, but I cannot call a class with a string. The reason I want call the class and not have it all in an if function is so that I may incorporate more methods.
Here is how it will run currently:
public class textadventure {
public method(String room){
if(room==street){street.enterRoom();}
}
}
public class street{
public enterRoom(){
//do stuff and call other methods
}
}
The if statement tests for every class/room I create. What I would like the code to do is automatically make the string room into a class name that can be called. So it may act like so:
Public method(string room){
Class Room = room;
Room.enterRoom();
}
I have already looked into using Class.forName, but all the examples were too general for me to understand how to use the function. Any help would be greatly appreciated, and if there is any other necessary information (such as more example code) I am happy to provide it.
-Sebastien
Here is the full code:
import java.awt.*;
import javax.swing.*;
public class Player extends JApplet{
public String textOnScreen;
public void start(){
room("street1");
}
public void room(String room){
if(room=="street1"){
textOnScreen=street1.enterRoom();
repaint();
}
if(room=="street2"){
textOnScreen=street2.enterRoom();
repaint();
}
}
public void paint(Graphics g){
g.drawString(textOnScreen,5,15);
}
}
public abstract class street1
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on a street running from North to South.";
return textToScreen;
}
}
public abstract class street2
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on another street.";
return textToScreen;
}
}
Seeing as you are rather new to programming, I would recommend starting with some programs that are simpler than a full-fledged adventure game. You still haven't fully grasped some of the fundamentals of the Java syntax. Take, for example, the HelloWorld program:
public class HelloWorld {
public static void main(String[] args) {
String output = "Hello World!"
System.out.println(output);
}
}
Notice that public is lowercased. Public with a capital P is not the same as public.
Also notice that the String class has a capital S.* Again, capitalization matters, so string is not the same as String.
In addition, note that I didn't have to use String string = new String("string"). You can use String string = "string". This syntax runs faster and is easier to read.
When testing for string equality, you need to use String.equals instead of ==. This is because a == b checks for object equality (i.e. a and b occupy the same spot in memory) and stringOne.equals(stringTwo) checks to see if stringOne has the same characters in the same order as stringTwo regardless of where they are in memory.
Now, as for your question, I would recommend using either an Enum or a Map to keep track of which object to use.
For example:
public class Tester {
public enum Location {
ROOM_A("Room A", "You are going into Room A"),
ROOM_B("Room B", "You are going into Room B"),
OUTSIDE("Outside", "You are going outside");
private final String name;
private final String actionText;
private Location(String name, String actionText) {
this.name = name;
this.actionText = actionText;
}
public String getActionText() {
return this.actionText;
}
public String getName() {
return this.name;
}
public static Location findByName(String name) {
name = name.toUpperCase().replaceAll("\\s+", "_");
try {
return Enum.valueOf(Location.class, name);
} catch (IllegalArgumentException e) {
return null;
}
}
}
private Location currentLocation;
public void changeLocation(String locationName) {
Location location = Location.findByName(locationName);
if (location == null) {
System.out.println("Unknown room: " + locationName);
} else if (currentLocation != null && currentLocation.equals(location)) {
System.out.println("Already in room " + location.getName());
} else {
System.out.println(location.getActionText());
currentLocation = location;
}
}
public static void main(String[] args) {
Tester tester = new Tester();
tester.changeLocation("room a");
tester.changeLocation("room b");
tester.changeLocation("room c");
tester.changeLocation("room b");
tester.changeLocation("outside");
}
}
*This is the standard way of formating Java code. Class names are PascalCased while variable names are camelCased.
String className=getClassName();//Get class name from user here
String fnName=getMethodName();//Get function name from user here
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(className);// get the Class
Object inst = thisClass.newInstance();// get an instance
// get the method
Method fn = thisClass.getDeclaredMethod(fnName, params);
// call the method
fn.invoke(inst, paramsObj);
The comments below your question are true - your code is very rough.
Anyway, if you have a method like
public void doSomething(String str) {
if (str.equals("whatever")) {
// do something
}
}
Then call it like
doSomething("whatever");
In Java, many classes have attributes, and you can and will often have multiple instances from the same class.
How would you identify which is which by name?
For example
class Room {
List<Monster> monsters = new ArrayList <Monster> ();
public Room (int monstercount) {
for (int i = 0; i < monstercount; ++i)
monsters.add (new Monster ());
}
// ...
}
Monsters can have attributes, and if one of them is dead, you can identify it more easily if you don't handle everything in Strings.

How to have a method have different input types java

I have a program on my computer that simulates a server on the internet and the fake server needs to be able to send multiple data types to some classes. Like for instance at one point of the program the server needs to send an int to a class then convert that int to a string and send it to another.
Basically what I am asking is if a method can have multiple data types for an input(Does this make sense? if not ill try to explain better). Is there any way to do this without creating many different methods?
Edit: Also is there a way to tell the difference between the types passed in (to prevent errors)
You can have a method which takes Object which is any type. In Java 5.0 and later primitives will be auto-boxed and passed as an object as well.
void method(Object o);
can be called using
method(1);
method("hello world");
method(new MyClass());
method(null);
If I understand correctly, you're asking if a method foo() can have multiple different inputs for its parameters
That way foo(Integer i) and foo(String s) are encased in the same method.
The answer: yes, but it's not pretty
foo(Object o)
Is your method declaration
Now you need to sort out the different types of possibilities
if(o instanceof Integer){
stuff();
} else if (o instanceof String){
moreStuff();
}
Just chain those else/if statements for the desired result.
What you want are Generic methods or classes.
to check what type an object is you'll have to use the 'instanceof' method
you can either make an entire class generic or just a single method, an example of a generic class:
package javahowto;
public class Member<T> {
private T id;
public Member(T id) {
this.id = id;
}
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
public static void main(String[] args) {
Member<String> mString = new Member<String>("id1");
mString.setId("id2");
System.out.printf("id after setting id: %s%n", mString.getId());
//output: id after setting id: id2
Member<Integer> mInteger = new Member<Integer>(1);
mInteger.setId(2);
System.out.printf("id after setting id: %d%n", mInteger.getId());
//output: id after setting id: 2
}
Now you now what to look for I'm sure you'll find the best solution to your problem.
check out:
http://download.oracle.com/javase/tutorial/java/generics/index.html
http://en.wikipedia.org/wiki/Generics_in_Java
...
Well I have also wondered and wrote below block. I think instanceof better but I tried getclass.
public static void main(String[] args){
System.out.println(method("This is a test"));
}
private static String method(Object o){
System.out.println(o.toString());
String status = "";
String className;
String[] oList = {"Double","Integer","String","Double","Float","Byte","Short","Long","Character","Boolean" };
for(int i = 0;i<oList.length;i++){
className = "java.lang." + oList[i];
Class testClass;
try {
testClass = Class.forName(className);
if(o.getClass().equals(testClass)){
status = "Your object is " + oList[i];
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return status;
}
You could use the "hashed adapter" pattern.
Public interface Adapter {
Public void handle(object o);
}
Public class StringAdapter implements Adapter {
Public void handle(String st) { // stuff ...
}
Public class IntegerAdapter implements Adapter {
Public void handle(Integer intgr) { // stuff ...
}
Private static final Map adapters = new HashMap();
Adapters.put(string.class, new stringAdapter());
Adapters.put(Integer.class, new IntegerAdapter());
Public void handleMe(Object o) {
Adapters.get(o.getClass()).handle(o);
}
Ive always liked this more than the ol' cascade of ifs and else's.
On my iPad so sorry about formatting and terseness and speellling.

Categories