Answer the question
In order to leave comments, you need to log in
How to access an instance of a class?
I'm learning java myself, tell me how to refer to another class other than declaring it again?
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
Dog dog = new Dog();
cat.setAge(8);
System.out.println( cat.getAge() );
}
}
public class Dog {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Cat {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void question() {
// как тут обратится к Dog?
Dog dog = new Dog(); // так?
}
}
Answer the question
In order to leave comments, you need to log in
You are working with an instance of a class, that is, an object.
If you want to work with the data of the Dog class in Cat, then create an object, that is, as you wrote
1) pass this class as an argument
2) If you need to instantiate a class and do something with it, then yes:
public void question() {
Dog dog = new Dog();
}
public void question(Dog dog) {
int age = dog.getAge();
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.setName("Vasyka");
Dog dog = new Dog();
dog.setName("Barbos");
Human human = new Human();
human.setCat(cat);
human.setDog(dog);
System.out.println(human.getDog().voice());
System.out.println(human.getCat().voice());
}
}
interface Animal {
String voice();
}
abstract class Pet implements Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Dog extends Pet {
@Override
public String voice() {
return getName() + " says Woof";
}
}
class Cat extends Pet {
@Override
public String voice() {
return getName() + " says Meaw";
}
}
class Human {
private Pet cat;
private Pet dog;
public Pet getCat() {
return cat;
}
public void setCat(Pet cat) {
this.cat = cat;
}
public Pet getDog() {
return dog;
}
public void setDog(Pet dog) {
this.dog = dog;
}
}
public void question(Dog dog){
//Тут соответственно, то что ты хочешь от пса
}
Cat brit = new Cat();
Dog mops = new Dog();
brit.question(mops) //кот обратился к собаке через метод question
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question