Syntax on printing objects? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Directions: http://imgur.com/kw6A0JX
I don't think I am printing out the objects correctly. My teacher helped me with the first part so I believe I am assigning them correctly. When printing them out, do I use "this" command? What is the right syntax for this type of situation?
Thank you.
public static void main(String [ ] args) {
Dog1 Rover = new Dog1("Rover", 4);
Sheep1 Wooly = new Sheep1("Wooly", 4);
Duck1 Daffy = new Duck1("Daffy", 2);
Cat1 Ketty = new Cat1("Ketty", 4);
System.out.println(name.Dog1, getHello.Dog1, isCarnivorous.Dog1, isMammal.Dog1);
System.out.println(name.Sheep1, getHello.Sheep1, isCarnivorous.Sheep1, isMammal.Sheep1);
System.out.println(name.Duck1, getHello.Duck1, isCarnivorous.Duck1, isMammal.Duck1);
System.out.println(name.Cat11, getHello.Cat1, isCarnivorous.Cat1, isMammal.Cat1);
}
Updated:
public abstract class Animal1 { //creating Animal1 which is the base and parent class, it is abstract so abstract classes can be created below
private String animalName; //defining animalName as private
public int numberOfLegs; //# of legs as public
public Animal1(final String name){ //first constructor with only assigning name
animalName = name;
}
public Animal1(final String name, final int legs){ //second constructor assigning both name and number of legs
animalName = name;
numberOfLegs = legs;
}
public String getName(){ //first getMethod for animalName
return animalName;
}
public int getLegs(){ //second getMethod for returning numberOfLegs
return numberOfLegs;
}
public boolean isMammal(){ //returning true value with boolean
return true;
}
public boolean isCarnivorous(){ //returning true value with boolean
return true;
}
public abstract String getHello(); //creating an abstract method, possible because base class is also abstract
}
public class Cat1 extends Animal1{ //child class of Animal1
public Cat1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 4);
}
#Override
public String getHello(){ //Overriding getHello to return "Meow"
return "Meow";
}
}
public class Dog1 extends Animal1{ //another child of Dog1
public Dog1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 4);
}
#Override
public String getHello(){ //Overriding getHello to return "Woof"
return "Woof";
}
}
public class Duck1 extends Animal1{ //third child class of Animal1
public Duck1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 2);
}
#Override
public boolean isMammal(){ //Overriding isMammal() function to return false, as a duck is not a mammal
return false;
}
#Override
public boolean isCarnivorous(){ //Overriding isCarnivorous() function to return false as a duck is not a carnivore
return false;
}
#Override
public String getHello(){ //Overriding getHello to return "Quack"
return "Quack";
}
}
public class Sheep1 extends Animal1{ //fourth child class of Animal1
public Duck1(final String name){ //Creating class constructor taking a name, within the constructor call the parent class constructor taking one argument
super(name, 2);
}
#Override
public boolean isCarnivorous(){ //Overriding isCarnivorous() function to return false as a sheep is not a carnivore
return false;
}
#Override
public String getHello(){ //Overriding getHello to return "Baa"
return "Baa";
}
}
public static void main(String [ ] args) {
Dog1 Rover = new Dog1("Rover", 4);
Sheep1 Wooly = new Sheep1("Wooly", 4);
Duck1 Daffy = new Duck1("Daffy", 2);
Cat1 Ketty = new Cat1("Ketty", 4);
System.out.println(Rover.getName() + ", " + Rover.getHello() + ", " + Rover.isCarnivorous() + ", " + Rover.isMammal());
System.out.println(Wooly.getName() + ", " + Wooly.getHello() + ", " + Wooly.isCarnivorous() + ", " + Wooly.isMammal());
System.out.println(Daffy.getName() + ", " + Daffy.getHello() + ", " + Daffy.isCarnivorous() + ", " + Daffy.isMammal());
System.out.println(Ketty.getName() + ", " + Ketty.getHello() + ", " + Ketty.isCarnivorous() + ", " + Ketty.isMammal());
}

Your syntax is wrong. You need to refer to the variable by name, not by class. And the method comes after the object. And System.out.println() doesn't accept multiple arguments. Try this:
System.out.println(Rover.getName() + ", " + Rover.getHello() + ", " + Rover.isCarnivorous() + ", " + Rover.isMammal());
Similarly for the other lines.

You've got your syntax reversed. If these are all methods that you're calling, then they're done like Dog1.name(). If they're just public variables, you can call them like Dog1.name.
Also, a word of advice - most object instants in java follow the syntax of first word lowercase, following words uppercase (like your methods). Not crucial, but helpful to know.
Edit: Yep, it's just what the first line of this answer reads. To get the boolean from your animal class, just call them with first the object's name, then .exampleMethod().
Also, for your print statements, the println method might print the statements funny if you leave it as it is. What you can do instead is just add some strings in between like so:
System.out.println("Name: " + Dog1.getName() + ", Hello: " + Dog1.getHello()...); // rest of line excluded for brevity

The keyword this refers to the current object.
public class Test
{
public static void main(String[] args)
{
Dog1 dog = new Dog1("Rover", 4);
System.out.println(dog.name() + " " + dog.hello() + " " + dog.carnivorus() + " " + dog.mammal() + ".");
}
}
class Dog1
{
private String name;
private int age;
private String hello;
private boolean carnivorus;
private boolean mammal;
public Dog1(String name, int age)
{
this.name = name;
this.age = age;
this.hello = "woof woof";
this.carnivorus = true;
this.mammal = true;
}
public String name()
{
return this.name;
}
public String hello()
{
return this.hello;
}
public boolean carnivorus()
{
return this.carnivorus;
}
public boolean mammal()
{
return this.mammal;
}
}

Related

Why is value of variable not incremented in constructor

I created a program that creates a card, which will contain a number, name and status. I want the user to be able to set the name for the user of the card but I want the number to be sequential, so a new one for every card created starting at 1. I set the value of the first card at 1 and then call the method to increment its value for the next card inside the constructor but when I run it in a test class it always gives out number 2. Help's appreciated!
Leaving the variables, constructor, increment method, toString method and test class below.
public class CartaoCliente {
long numCartao = 1;
String nome;
Boolean estado;
public void incCartao(){
numCartao++;
}
public CartaoCliente(String nomeCartao){
incCartao();
this.nome = nomeCartao;
}
#Override
public String toString(){
return "Número: " + numCartao + ", Nome: " + nome; //overriden to print below
}
}
public class TesteCartao {
public static void main(String[] args) {
CartaoCliente c = new CartaoCliente("José");
CartaoCliente d= new CartaoCliente("Esdrubal");
System.out.println(c.toString());
System.out.println(d.toString());
}
}
solution from #Progman
public class CartaoCliente {
static long numCartao = 1;
String nome;
Boolean estado;
long novoNum;
public void incCartao(){
novoNum = numCartao++;
}
#Override
public String toString(){
return "Número: " + novoNum + ", Nome: " + nome; //overriden to print below
}
}

java Output does not match input for variables

Writing a main class to output from 2 other classes. There are 6 variables being passed but only the last 3 are printing correctly. The first 3 all return null. Here is the output:
DOG DATA
null is a null, a null dog.
The top trick is : Spinner.
The Corgi is 12 years old and weighs 20 pounds.
public class Dog {
// instance variables
public static String type;
public static String breed;
public static String name;
public static String topTrick;
// constructor
public Dog(String type, String breed, String name) {
type = "No type";
breed = "No breed";
name = "No name";
}
// methods
public static String setTopTrick(String trick) {
topTrick = trick;
return trick;
}
// method used to print Dog information
public String toString() {
String temp = "\nDOG DATA\n" + name + " is a " + breed +
", a " + type + " dog. \nThe top trick is : " +
topTrick + ".";
return temp;
}
}
ublic class Corgi extends Dog {
// additional instance variables
public static int weight;
public static int age;
// constructor
public Corgi(String type, String breed, String name, int pounds, int years) {
// invoke Dog class (super class) constructor
super(type, breed, name);
weight = pounds;
age = years;
}
// mutator methods
public static int setWeight(int pounds) {
weight = pounds;
return pounds;
}
public static int setAge(int years) {
age = years;
return years;
}
// override toString() method to include additional dog information
#Override
public String toString() {
return (super.toString() + "\nThe Corgi is " + age +
" years old and weighs " + weight + " pounds.");
}
}
public class Driver {
public static void main(String[] args) {
Corgi sleeper = new Corgi("Geriatric", "Pembroke Welsh", "Ein", 20, 12);
sleeper.setTopTrick("Spinner");
System.out.println(sleeper);
}
}
Literally everything in your program except main that is static should not be static. Static variables are not instance variables.
Also, your Dog constructor is incorrect, and should be
this.type = type;
this.breed = breed;
this.name = name;

Type Erasure and the Return type

class Person
{
String name;
String add;
Person(){}
#Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", add='" + add + '\'' +
'}';
}
public Person(String name, String add)
{
this.name=name;
this.add=add;
}
}
class PersonBuilder<E extends PersonBuilder<E>>{
String name;
String add;
E addName(String name)
{
this.name=name;
return (E)this;
}
E addAdd(String add)
{
this.add=add;
return (E)this;
}
Person build()
{
return new Person(name,add) ;
}
}
class Employee extends Person{
String doj;
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", add='" + add + '\'' +
", doj='" + doj + '\'' +
'}';
}
Employee(String name, String add, String doj)
{
super(name,add);
this.doj=doj;
}
}
class EmployeeBuilder extends PersonBuilder<EmployeeBuilder>{
String doj;
EmployeeBuilder addDoj(String doj)
{
this.doj=doj;
return this;
}
Employee build()
{
return new Employee(name,add,doj);
}
}
public class FluentBuilderRecursiveGenerics{
public static void main(String[] args) {
1. EmployeeBuilder eb=new EmployeeBuilder();
2. Employee e=eb.addName("kamal").addAdd("dcd").addDoj("45").build();
3. System.out.println(e);
4. PersonBuilder pb=new PersonBuilder();
5. Person p=pb.addName("Kamal").addAdd("dlf").build();
6. System.out.println(p);
}
}
I have two questions to ask in these lines of code. The lines of code are related to the Fluent(design pattern) Recursive Generics.
First is as Line 1, 2, 3 are running that means the Return type of PersonBuilder method is EmployeeBuilder, but I have also studied that the type erasure replaces the type with the bounds, So it should be replacing with PersonBuilder(EmployeeBuilder) and the program should not be running.
Because when in case of generics the input parameters of a function will be decided by the type Erasure.
The other question is what type Erasure is going to do for the line Number 4,5,6.
Can anyone explain?
Output:
Employee{name='kamal', add='dcd', doj='45'}
Person{name='Kamal', add='dlf'}
4, 5, 6:
Here there is no generic type parameter, hence the compiler will fallback on the
pre-generics behavior. No type-safeness. In effect it shows a design flaw here.
1, 2, 3:
Type erasure results in a runtime cast to EmployeeBuilder of the PersonBuilder object at addDoj.
About the pattern implementation and the parametrisation with the actual child class:
One can use the language feature that an overriden method may return any child class of the super method. This makes generic typing unneeded, but does not enforce the return type being the exact child class. And requires all methods in every child class to be overriden.
public class A {
String name;
A addName(String name) {
this.name = name;
return this;
}
}
class B extends A {
#Override
B addName(String name) {
return (B) super.addName(name);
}
}
public static void main(String args[]) {
B b = new B().addName("xxx");
System.out.println("name = " + b.name);
}

compare constructors objects Java

What an amazing platform! I hope im not asking a too stupid question but i have searched for an answer without success.
Q:
Is it possible to compare object values created by a constructor? Like if i want to make the animals fight and compare the "str" values against eachother.
My goal is to create the "fight" method in the Animal class, not in main. In that way, i can just call it like "dog.fight();
See my code for an example (sorry for my english)
public class Animal {
private int str;
private int agi;
private String name;
private String eyeColour;
public void set (int strenght, int agility, String _name){
str = strenght;
agi = agility;
name = _name;
}
public String get (){
System.out.println("Created a new animal named " + name +"! ");
System.out.println(name + "'s agility is " + agi);
System.out.println(name + "'s strenght is " + str);
return name + str + agi;
}
}
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Animal dog = new Animal ();
dog.set(8, 4, "Rambo");
dog.get();
System.out.println("");
Animal cat = new Animal ();
cat.set(2, 9, "Felix");
cat.get();
}
}
You need to create a method 'fight' in the Animal class the takes as parameter an Animal object and use it to return to you the result of the winner.
Here is the code :
public class Animal {
private int str;
private int agi;
private String name;
private String eyeColour;
public void set (int strenght, int agility, String _name){
str = strenght;
agi = agility;
name = _name;
}
public String get (){
System.out.println("Created a new animal named " + name +"! ");
System.out.println(name + "'s agility is " + agi);
System.out.println(name + "'s strenght is " + str);
return name + str + agi;
}
public String fight(Animal rival){
//Provide Comparison Logic Here
if(this.str>rival.str)return this.name;
if(this.str < rival.str)return rival.name;
return "No One ";
}
}
public class Hello {
public static void main(String[] args) {
Animal dog = new Animal ();
dog.set(8, 4, "Rambo");
dog.get();
System.out.println("");
Animal cat = new Animal ();
cat.set(2, 9, "Felix");
cat.get();
System.out.println(dog.fight(cat)+" is the winner! ");
}
}
A Small side notes here:
It would be much better to use constructors instead of set Method here, as normally setter and getter are created to set or get a single variable.
Also it's better to change the name of your get Method and override toString method.
Here's the modified code:
public class Animal {
private int str;
private int agi;
private String name;
private String eyeColour;
public Animal (int str, int agi, String name){
this.str = str;
this.agi = agi;
this.name = name;
}
#Override
public String toString(){
String description = "Created a new animal named " + name +"!\n";
description+=name + "'s agility is " + agi+"\n";
description+=name + "'s strenght is " + str;
return description;
}
public String fight(Animal rival){
//Provide Comparison Logic Here
if(this.str>rival.str)return this.name;
if(this.str < rival.str)return rival.name;
return "No One ";
}
}
public class Hello {
public static void main(String[] args) {
Animal dog = new Animal (8, 4, "Rambo");
System.out.println(dog);
System.out.println();
Animal cat = new Animal (2, 9, "Felix");
System.out.println(cat);
System.out.println(dog.fight(cat)+" is the winner! ");
}
}

add a prefix code displayed in toString method based on object subtype

I have written a simple program that has an Animal super type and a Dog and Cat subtypes. The subtypes inherit 3 instance variables, name, weightInKg, and animalId. Each subtype has its own unique boolean, barks and swims.
I have a Farm class that adds Animal object to an ArrayList and a method that displays the toString() methods of each object in the collection. I want to create a pre-fix code to be displayed instead of each objects unique animalId in the toString() method. For example, if it is a Dog subtype "d1" will be displayed for all Dog objects.
Is there a way to do this?
I know that the obvious answer would be to put the code in as the animalId but thats not what I am trying to accomplish. Thanks!`
Animal:
public class Animal {
private String name;
private double weightInKg;
private String animalId;
public Animal() {}
public Animal(String name, double weightInKg, String animalId) {
setName(name);
setWeightInKg(weightInKg);
setAnimalId(animalId);
}
//getters and setter ommitted
public String getAnimalId() {
return animalId;
}
public void setAnimalId(String animalId) {
this.animalId = animalId;
}
#Override
public String toString() {
return "Animal [name=" + name + ", weightInKg=" + weightInKg + ", animalId=" + animalId + "]";
}
}
Dog:
public class Dog extends Animal {
private boolean barks;
public Dog() {}
public Dog(String name, double weightInKg, String animalId, boolean barks) {
super(name, weightInKg, animalId);
setBarks(barks);
}
public boolean isBarks() {
return barks;
}
public void setBarks(boolean barks) {
this.barks = barks;
}
#Override
public String toString() {
return "Dog [barks=" + barks + ", toString()=" + super.toString() + "]";
}
}
Cat:
public class Cat extends Animal {
private boolean swims;
public Cat() {}
public Cat(String name, double weightInKg, String animalId, boolean swims) {
super(name, weightInKg, animalId);
setSwims(swims);
}
public boolean isSwims() {
return swims;
}
public void setSwims(boolean swims) {
this.swims = swims;
}
#Override
public String toString() {
return "Cat [swims=" + swims + ", toString()=" + super.toString() + "]";
}
}
Farm:
import java.util.ArrayList;
public class Farm {
private ArrayList < Animal > farm;
public Farm() {
farm = new ArrayList < Animal > ();
}
public void addToFarm(Animal newAnimal) {
farm.add(newAnimal);
}
public void displayAllAnimals() {
int counter = 0;
while (farm.size() > counter) {
System.out.println(farm.get(counter));
}
}
}
I'm not 100% clear on what you what the output to look like, perhaps an example would help.
However you could convert the Animal class to be abstract and add an abstract "prefix" method which all the subclasses would have to implement. For example:
public abstract class Animal {
...
protected abstract String prefix();
#Override
public String toString() {
return "Animal [prefix=" + prefix() + ", name=" + name + ", weightInKg=" + weightInKg + ", animalId=" + animalId + "]";
}
}
See https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

Categories

Resources