I am having a bit of trouble getting started on this Java assignment, and was hoping to get some guidance from you guys. My issue is pretty simple and straightforward... How do I take the tester method's input and start using "Dave" as the new name? How do I make Dave the instance variable and how do I start using that in the setName() and greetCrewMember() methods? After that's done, how would I assign Aruna? The main thing tripping me up is the instance variable and calling it in the methods. Thanks for any help given!
public class Hal9000
{
private String name;
public static void main(String[] args)
{
Hal9000 hal = new Hal9000("Dave");
System.out.println(hal.greetCrewMember());
System.out.println("Expected: Welcome, Dave");
System.out.println(hal.doCommand("engage drive"));
System.out.println("Expected: I am sorry, Dave. I can't engage drive");
hal.setName("Aruna");
System.out.println(hal.doCommand("power down"));
System.out.println("Expected: I am sorry, Aruna. I can't power down");
}
public String getName()
{
}
public void setName(String newName)
{
String name = newName;
return name;
}
public String greetCrewMember()
{
String message = "Welcome," + name ;
return message;
}
public String doCommand(String whatToDo)
{
}
}
The only thing you have to do is to define a parameterised constructor-
Hal9000(String name)
{
this.name=name;
}
This will cause your statement-
Hal9000 hal = new Hal9000("Dave");
to execute correctly and set the name to Dave. After this you can set the name to anything else by your setname method.
You would also want to define something in your getname method.
You should use the field name within the constructor and use this to instantiate it within the setter and constructor.
Hal9000(String name) {
this.name = name;
}
further instantiate as
Hal9000 instanceForDave = new Hal9000("Dave"); // would set the 'name' for this instance as 'Dave'
Hal9000 instanceForAruna = new Hal9000("Aruna");
The setter implementation should ideally also make use of this name only, something similar to the constructor in your case as:
public void setName(String newName) {
this.name = newName;
}
and then when you need to fetch the name attribute of the class, the getter would be helpful as
public String getName() {
return this.name;
}
public class Hal9000
{
private String name;
public Hal9000(String[] stringArray) {
name = stringArray[0];
}
public static void main(String[] args)
{
String[] stringArray = { "Dave"};
Hal9000 hal = new Hal9000(stringArray);
System.out.println(hal.greetCrewMember());
System.out.println("Expected: Welcome, Dave");
System.out.println(hal.doCommand("engage drive"));
System.out.println("Expected: I am sorry, Dave. I can't engage drive");
hal.setName("Aruna");
System.out.println(hal.doCommand("power down"));
System.out.println("Expected: I am sorry, Aruna. I can't power down");
}
public String getName()
{
return this.name;
}
public void setName(String newName)
{
this.name = name;
}
public String greetCrewMember()
{
String message = "Welcome," + getName() ;
return message;
}
public String doCommand(String whatToDo) {
return whatToDo;
}
}
Related
What I should change to print the name of chair, which is chairNumber1?
public class Employee {
private Chair s;
Employee(Chair s) {
this.s = s;
}
void showData() {
System.out.println("Name of chair : " + s);
}
}
public class Chair {
}
public class Hlavna {
public static void main(String[] args) {
Chair s = new Chair("chairNumber1");
Employee c1 = new Employee(s);
c1.showData();
}
}
Why when I want to print name of the Chair, which is chairNumber1, Java prints on console the address of chairNumber1, but not it's name?
You must be already aware of the fact that every class in Java inherits a class called Object by default. This class has a method toString() which returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object.
When you use System.out.println("Name of chair : " + s);, it will call s.toString() but since you haven't provided your own implementation of toString() inside class Chair, it will call the toString() method of class Object which is the default superclass of class Chair. This is why you see the value which you think as the address of chairNumber1.
To get your desired String, you need to override the toString() method something like:
public class Chair {
private String name;
public Chair(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
define a method inside your chair class that returns the name or override the toString method.
example:
public class Chair{
private String chairName;
Chair(String chairName){
this.chairName = chairName;
}
public String toString(){
return chairName;
}
}
now inside showdata() call toString():
void showData(){
System.out.println("Name of chair : " + s.toString());
}
There are a couple of things going on here.
You have created a chair object in your main method of your Hlavna class. To this Chair object you have provided an argument, although from the code above Chair does not take an argument.
In the same way that you have made the Employee class take an argument of chair, you should take the Chair take an argument of name, like so:
public class Chair
{
private String name;
Chair(String chairName)
{
this.name = chairName;
}
}
Now this isn't enough. When you print any Java object, under the hood what is really happening is the object's toString method is called. By default this prints the object's address, but you can override that by implementing the method yourself, like so:
public class Chair
{
private String name;
Chair(String chairName)
{
this.name = chairName;
}
public String toString()
{
return this.name;
}
}
Now, when you print a chair object it will call the Chair object's implementation of toString, which here returns the chair's name.
Your employee class is correctly printing the "toString()" method of the chair that you pass to it as you construct it, but currently that looks like an address. If you change the Chair object to the above code, that will instead print the chair name, which is what you are after.
The full code would look like this:
public class Employee
{
private Chair s;
Employee(Chair s)
{
this.s = s;
}
void showData()
{
System.out.println("Name of chair : " + s);
}
}
public class Chair
{
private String name;
Chair(String chairName)
{
this.name = chairName;
}
public String toString()
{
return this.name;
}
}
public class Hlavna
{
public static void main(String[] args)
{
Chair s = new Chair("chairNumber1");
Employee c1 = new Employee(s);
c1.showData();
}
}
public class Chair {
private String name;
public Chair(String name) {
this.name = name;
}
#Override
String toString() {
return name;
}
}
I have a question about this code:
public class Musician {
private String name;
public String instrument;
public Musician(String name, String instrument){
this.name= name;
this.instrument= instrument;
}
public String getInstrument() {
return instrument;
}
public String getName() {
return name;
}
private String getClassName(){
return "Musician ";
}
public void play(){
System.out.println("[M] "+getClassName() + " plays music.");
}
public void printInfo(){
play();
System.out.println("[M] Class name: "+ getClassName());
System.out.println("[M] Instrument: "+ getInstrument());
}
}
public class RockMusician extends Musician{
public String instrument;
public RockMusician(String name, String instrument) {
super(name, instrument);
this.instrument= instrument + " and drums";
}
public String getClassName(){
return " RockMusician ";
}
public void play(){
System.out.println("[RM] "+ getClassName() + getName() + " breaks his "+ super.getInstrument() + "!");
}
}
public class IsraelyRockMusician extends RockMusician {
public IsraelyRockMusician(String name, String instrument) {
super(name, instrument);
}
public String getInstrument() {
return instrument;
}
public String getName(){
return super.getName() + " the king";
}
public String getClassName() {
return " IsraelyRockMusician ";
}
}
public class Testing {
public static void func(Musician m){
System.out.println("I've got a musician!");
}
public static void func(RockMusician m){
System.out.println("I've got a rock musician!");
}
public static void main(String[] args) {
Musician m3 = new IsraelyRockMusician("Chanoch", "guitar");
m3.printInfo();
}
}
I have IsraeliRockMusician who inherits RockMusician who Inherits Musician,
I then make a Musician m3 with the name "chanoch" and instrument "guitar"
and I active the method, print Info,
because the printInfo is in the father -> RockMusician which contains 3 methods on itself-> play(),getClassName(),and getInstrument(),
my question is, when the method showinfo runs, play is going all the way to the overwriten method and prints "[RM] IsraelyRockMusician Chanoch the king breaks his guitar!",
now this is fine, but the next line is "[M] Class name: Musician ", which means the getClassName was given "Musician" and Im asking why its not "IsraeliRockMusician" since the method was overwritten.
I'm sorry if the question is a bit hazey.
The problem is that the method of the base class has private access.
private String getClassName(){
return "Musician ";
}
Change it to public/protected so you can override it.
Instead of having a function where you hardcode the class name, you should use the following:
public class Foo {
public void printClassName() {
System.out.println(this.getClass().getName());
}
}
This way, if you change your class name, you don't need to update the method that you've written. One caveat to this is if you run an obfuscation tool against your code, the class name may be replaced with random characters. In that case, you can create a const string in your class and refer to that instead.
public class Sample1 {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
Sample1 s1= new Sample1();
s1.setName("Abc");
}
}
public class Sample2 {
public static void main(String[] args) {
Sample1 n2= new Sample1();
System.out.println(n2.getName());
}
}
I have two classes Sample1 and Sample2 two. I am allocating string value using setter method and returning in another class by using getter method, but an output is null. Why null is an output and how to get string value from one call to another class?
I think you misunderstood the main method, maybe I am wrong, however only one main method is executed.
If you run Sample2.main - on Sample1 you are not setting a name so it is null (Sample1.main is never executed).
If you run Sample1.main - Sample1 is created and assigned a name.
So either assign the name in the Sample2.main:
public static void main(String[] args) {
Sample1 n2= new Sample1();
n2.setName("xxx");
System.out.println(n2.getName());
}
or do it via constuctor.
public class Sample1 {
private final String name;
public String getName() {
return name;
}
public Sample1(String name) {
this.name = name;
}
}
Consider the code :
Sample1 n2= new Sample1();
System.out.println(n2.getName());
Here the Name is not set , So you need to set the name before getting the name.
Sample1 n2= new Sample1();
n2.setName("name goes here");
System.out.println(n2.getName());
Also, you can try parameterized constructor in the Sample1 class and access like in sample2 class:
Sample1 n2= new Sample1("your name goes here");
System.out.println(n2.getName());
The constructor will be :
public Sample2(String name){
this.name = n;
}
3 thing you can add method in Sample1 class and access it in Sample2 class.
I don't want to set String value in Sample2 class, need to assign string value in Sample1 only, after that i need that string value in Sample2 class
public class Sample1 {
private String _name;
public String getName() {
return _name;
}
private setName(String name) {
_name = name;
}
public SetNameHelper(){
setName("somestring");//You will be setting the name in Sample 1
}
}
public class Sample2 {
public static void main(String[] args) {
Sample1 n2= new Sample1();
n2.SetNameHelper();
System.out.println(n2.getName());//You will be getting Name in Sample 2 class
}
}
class Sample2 {
Sample1 sample1;
Sample2(Sample1 sample){
this.sample1 = sample;
}
private String getSample1Name() {
return this.sample1.getName();
}
public static void main(String[] args) {
Sample1 sample1 = new Sample1();
sample1.setName("Abc");
Sample2 n2= new Sample2(sample1);
System.out.println(n2.getSample1Name());
}
}
I think I understand you confusion: you mistake a main function for a constructor!
I noticed that you created a main function in each class, whose only role is to create an instance and set the internal fields of the class. It's probably a Constructor you were looking for.
Here's the deal:
A main method is the entry point of a program. It just stays, to run me: begin executing this code. You probably (99.9% of the case) need only one main method per project.
A Constructor is a method which creates an instance of, each class, i.e. an object you can manipulate elsewhere in your code. Read up on Object-Oriented Programming
So here is your example, fixed (I believe), in a way that can bring sample1 value into an sample2, as you say:
public class Sample1 {
public String name;
public String Sample1(String initialName){
this.name = initialName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Sample2{
public String name;
public String Sample2(String initialName){
this.name = initialName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ProgramEntryPoint{
public static void main(String[] args) {
Sample1 s1 = new Sample1("a name");
System.out.println("Initial sample1 name: " + s1.getName());
s1.setName("a New Name!");
System.out.println("New sample1 name: " + s1.getName());
Sample2 s2 = new Sample2(s1.getName());
System.out.println("Initial sample2 name: " + s2.getName());
}
}
Which, once you run ProgramEntryPoint.main, will print:
Initial sample1 name: a name
New sample1 name: a New Name!
Initial sample2 name: a New Name!
This is all simple Java stuff, you should read up a few basic tutorials (the ones on oracle website are a good start)
I am new to java programming and know it is possible to have class as an attribute as another.
For instance you could have publisher as one class and strategyGame as another. Is there a way to have it so a method in publisher class that counts the amount of strategyGame objects there is, therefore ability to display the amount of strategy games that publisher has published?
Thank you
Here is a simple Snippet to keep you going..
Image you have StrategyGame class
public class StrategyGame {
private String name;
public StrategyGame(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And inside your Publisher class you keep a List of StrategyGame objects
public class Publisher {
List<StrategyGame> games;
public Publisher() {
games = new ArrayList<>();
}
public void publishGame(String name) {
games.add(new StrategyGame(name));
}
public int getHowManyGamesCreated() {
return games.size();
}
}
Now how to use it in your main?
public static void main(String[] args) {
Publisher publisher = new Publisher();
publisher.publishGame("Pacman");
publisher.publishGame("Asteroids");
System.out.println(publisher.getHowManyGamesCreated());
}
Customer.java:17: error: cannot find symbol
super.display();
^
symbol: method display()
1 error
This what is happening when I compile my program. How do I display the objects data in the Customer subclass?
import java.util.Scanner;
public class Person {
private String name;
private String address;
private String number;
//No Argument constructor//
public Person() {
name = "";
address = "";
number = "";
}
//Explicit value constructor//
public Person(String num, String nam, String add) {
number = num;
name = nam;
address = add;
}
//Accessor method//
public String getName() {
return name;
}
//Mutator method//
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTelephoneNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String toString() {
return name + "\n" + address + "\n" + number;
}
}
The subclass:
public class Customer extends Person {
public Customer(String num, String nam, String add) {
super(num, nam, add);
}
public boolean checkResponse(char response) {
if (response == 'Y') {
return true;
}
return false;
}
public void display() {
super.display();
}
}
In order for super.display() to work, you require a method called display() in your parent class.
Since you have no such method, Java will not allow the code you have to compile.
Since it seems you're trying to show useful information about the object when it's printed, why not override toString() again? The caveat here is that you don't have any more meaningful information to show about it being a Customer over it being a Person (there's no Customer-specific fields, so the inheritance relationship is moot).
You may want to consider adding more info to differentiate a Customer from a Person, then override toString().
The error occurs because there is no display() method in the Person class. So you cant invoke a non existing method using super.display()
So change the display() method in Customer to
public void display() {
System.out.println(super.toString());
}
As the error is trying to tell you, super.display() doesn't exist.
You can simply access the number, name or address directly. Modify the display() method, remove super.display() like below.
public void display()
{
System.out.println("Customer telephone number:" + number);
}
Super keyword in java is related to parent class and Super.display() means you are calling the display method of the parent class.Your parent class is person as you are extending it public class Customer extends Person {
But there is no display() in person hence your are getting compilation error
You don't have display() function defined in parent class(Pesron);