Java Inheritance

So, I was trying to find the right way to get what should be a fairly simple inheritance to work (the way I want;)), and I fail. Consider this:


class Parent
{
  public string name = "Parent";

  public Parent() {};
  public doStuff()
  {
     System.out.println(name);
  }
}

class Child extends Parent
{
  public string name = "Child";
  public Child()
  {
    doStuff();
  }
}

, , . , Java , , - - , , , , ? , , -, / . , get/sets , super(), , , .

.

+3
6

getter, " ". , " " ((c)) .

class Parent {
    public void doStuff() {
        System.out.println(getName());
    }

    public String getName() {
        return "Parent";
    }
}

class Child extends Parent {
    public Child() {
        doStuff();
    }

    public String getName() {
        return "Child";
    }
}

Parent, .


"". .

class Parent {
    private final String name;

    // don't let use to invoke this constructor, only for child classes
    protected Parent(String name) {
        this.name = name;
    }

    // public constructor for users
    public Parent() {
        this("Parent");
    }

    public void doStuff() {
        System.out.println(name);
    }
}

class Child extends Parent {
    public Child() {
        super("Child");
        doStuff();
    }
}

, Java, , -?
Java ++ ( ), , .
, . .

+8

name ? , "-- " "-- "? , Parent.

Parent , ? , ?

, , .

+6

name . , Child name .

, , Parent. super("Child") .

, , . .

+3

, . , name .

class Parent {   
    protected string name;

    public Parent() { name = "parent"};   
    public doStuff() {
        System.out.println(name);   
    }
}

class Child extends Parent {   
    public Child() {
        name = "child";
        doStuff();
    }
}
+2

, , Java. Java , , .

, private getter , .

:

class Child extends Parent {
    public Child() {
        name = "Child";
        doStuff();
    }
}

@shoebox639 , final. ( - ...)

+1

You do not need to override the member variable in the subclass. You can write your code as @Stephen C says

<pre>
<code>
class Child extends Parent {
    public Child() {
        name = "Child";
        doStuff();
    }
}
</code>
</pre>

In your post

I would like my base class to contain some functions that work with the member variables provided / defined by this subclass.

First you write your superclass, and at this point your superclass does not know about your subclass.

0
source

Source: https://habr.com/ru/post/1770773/


All Articles