N
N
NikitkOS2016-04-03 21:12:26
Java
NikitkOS, 2016-04-03 21:12:26

Can you help me figure out inheritance in Java?

I recently asked a question on this topic, but I did not fully understand it. I wrote the code, there are no errors, as well as the proper result. It is necessary that it displays Tuzik's age (i.e. 5), but displays 0. Please explain.

public class Pet {
    public static Dog tuzik = new Dog();
      String name;
        int age, weight, cost;
 }
  public class Dog extends Pet{
    public void Tuzik(){
        tuzik.age = 5;
    }
 }
  public class Main extends Dog{
    public static void main(String[]args){
   	 System.out.print(tuzik.age);
    }
 }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pi314, 2016-04-03
@NikitkOS

What you wrote makes no sense (even if it compiles)! If I correctly understood the meaning of the idea, which is VERY difficult from what was written, then it should be something like this:

public abstract class Pet {
  String name;
  int age;
  int weight;
  int cost;
}
...
public class Dog extends Pet {
  public Dog(String name, int age){
    this.name = name;
    this.age = age;
  }
}
...
public class Main {

  public static void main(String[] args) {
    Pet tuzik = new Dog("Tuzik", 5);
    System.out.print(tuzik.age);
  }

}

This is the closest thing to writing and will work as desired, but it's still HORRIBLE from the point of view. OOP, so consider this only as an illustration, not as an example to follow.
Notice the " public Dog(String name, int age){..." is a constructor. It doesn't have a type. It is called when the class is instantiated ( ... = new Dog("Tuzik", 5);) and returns an instance of the class (an object). Only after this the fields of the object are initialized with some values. Before that, there is nothing in them in this example (more precisely, right after the creation of the object and before the completion of its constructor, 0 and null are everywhere in name).
If you don't understand something, feel free to ask, but keep in mind that until you figure it out, it's pointless to continue discussing the details (for example, why the Pet class is abstract).

K
Konstantin Malyarov, 2016-04-03
@Konstantin18ko

Call class.method, class.variable.
Dog class, Tuzik() method.
To make it easier. First, you call what has the word class in the line, and then what you want to see (if anything, the IDE will tell you).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question