#Inheritance

1 messages · Page 1 of 1 (latest)

heavy echo
#

"A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass."

i dont fulyl get this sentence.

sudden bloomBOT
#

<@&987246399047479336> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#
TJ-Bot
"A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass." i dont fulyl

ess to the private members of its enclosing class. Inheritance in Java allows a subclass to inherit the properties and behaviors of its superclass, enabling code reusability and promoting a hierarchical structure in object-oriented programming.

Subclasses can extend the functionality of their superclass by adding new methods or overriding existing ones. This allows for polymorphism, where an object can be treated as an instance of its superclass or any subclass. The super keyword can be used to access superclass members from within a subclass.

Inheritance also facilitates code organization and maintenance by promoting code reuse through the concept of "is-a" relationships. For example, a Dog class can inherit from an Animal class because a dog is a type of animal.

Java supports single inheritance, where a subclass can only extend one superclass, but multiple inheritance can be achieved through interfaces. Interfaces define a contract that implementing classes must follow, allowing for multiple types of behavior to be added to a class without creating complex inheritance hierarchies.

Overall, inheritance is a fundamental concept in Java that promotes code reuse, hierarchical organization, and polymorphism in object-oriented programming."

heavy echo
#

Super
Nested -----> Sub Class

#

does it mean Sub Class of a nested class can manipulate super class of nested class

blissful aspen
#

its about visibility

#

private means visible within the same class

#

that includes nested classes

heavy echo
blissful aspen
#
class Outer {
  private static void hello() { System.out.println("huhu"); }

  static class Inner {
    void foo() { Outer.hello(); }
  }
}
#

now, a third class can write

steel veldt
#

its a about leakage

blissful aspen
#
Outer.Inner inner = new Outer.Inner();
inner.foo();

and that will print huhu

#

but cant write

#
Outer.huhu();

directly

heavy echo
#

you mean Outer.hello()

blissful aspen
#

yeah

#

now, even if foo would be marked protected, so:

#
class Outer {
  private static void hello() { System.out.println("huhu"); }

  static class Inner {
    protected void foo() { Outer.hello(); }
  }
}
#

someone can access hello() indirectly by extending Inner

#
class Third extends Outer.Inner {
  public void bar() { foo(); }
}
#

the method is visible to the subclass. so the subclass can use it

#

none of that is really a concern of any sort. it just highlights that u have to understand how visibility works and that ur in charge of defining what ur class is allowed to do and what not

#

if u dont want subclasses of Inner to have access to foo(), it shouldnt be protected

#

if u dont want people to use hello(), the class shouldnt have a nested class

#

and so on

heavy echo
#

that means a subclass of Inner , also inheritated Outer ?

blissful aspen
#

it doesnt inherit it

#

it also cant call it

#

but it can call foo

#

since thats protected

#

and foo can call hello since Inner is nested

steel veldt
#

a nested class has access to the members of it's enclosing class

#

if another class extends that class, there could be leakage (thats what the statement is suggesting)

blissful aspen
#

provided the nested class didnt define its interface properly

heavy echo
blissful aspen
#

Inner can call hello(). scroll up

#

#1257263125003112518 message

#

private doesnt mean "only i can use it"

#

it means "everyone in this class can use it"

#

and that includes by definition nested classes

#

so u just have to understand the visibility modifiers better

steel veldt
#

therefore, a nested class inherited by a subclass has indirect access to private members

heavy echo
steel veldt
#

if you define a nested class, it has access to the private members of the encolsing class

#

thats the prerequisite

#

does that make sense?

#

if not, then this entire concept wont make much sense

heavy echo
#

through protected and below methods ?

blissful aspen
#

yes

#

its indirect

#

see, the thing is the following

#

suppose a bank employee who has access to the vault

#

u dont have access to the vault

#

but u could force the employee to open it up for u

#

that way, u indirectly access it

#

its similar here

#

Inner has access to it

#
class Vault {
  private takeOutMoney() { ... }

  class Employee {
    public void openVault() { takeOutMoney(); }
  }
}
#

in this example, since Employee was so stupid to make openVault public, visitors can now open the vault and take out money

#

since they can just kindly ask the employee to open the vault

#
employee.openVault();
#

anyone can do this

#

since its public

#

and by that indirectly call takeOutMoney()

#

Vault made the mistake to have Employee a nested class

#

and Employee made the mistake to have openVault public

#

if people design their classes correctly, nothing bad happens

steel veldt
#

if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass

#

like zabu mentioned, its only a problem with poorly designed classes

heavy echo
#

like this

heavy echo
#

why is this not possible?

#

want to check with instanceof

#

oh, only possible with classes

#

obj == obj not possible

#

and why is the class cast necessary in this if-statement ?
is
MountainBike myBike = obj;

not enought this the condition checks if its true ?

edgy badge
#

t1.getClass().isInstance(object)

heavy echo
#

Quinteger 🤩

#

context pls 😄

#

is a class not an instance of the same class ?

edgy badge
#

class is a blueprint for objects

#

this is basic OOP

#

class is a blueprint, object is a thing created using that blueprint

#

when you do an instanceof check, you want to check whether an object matches a blueprint

heavy echo
#

public class SuperClass {
    protected int a=5;
    protected int b=3;
    protected SuperClass[] o;
    
    SuperClass(){
        
    }
    
    SuperClass(int a, int b){
        this.a=a;
        this.b=b;
    }

    private static void hello() {
        System.out.println("huhu");
    }

    static class SubClass {
        protected void foo() {
            SuperClass.hello();
        }
        
        SubClass[] subArray;
        
        protected int add(int a, int b) {
            return a+b;
        }
    }
    
    public static void main(String[]args) {
        SuperClass sup2 = new SuperClass.SubClass();
    }
}
#

does anyone knwo why the object creation wont work

#

omg

#

Its nested and not sub

heavy echo
#

alathreon my fav java professor are you theree

proven current
#

SubClass is not a type of SuperClass, so it can't be assigned here

SuperClass sup2 = new SuperClass.SubClass();
```a nested class doesn't inherit from its containing class
heavy echo
#

public class SuperClass {
//    Instanzvariable
    protected int gebJahr;
    protected String name;

    protected SuperClass[] supArray = new SuperClass[10];

//    Konstruktoren
    SuperClass() {

    }

    SuperClass(String name, int gebJahr) {
        this.gebJahr = gebJahr;
        this.name = name;
    }

//    Instanzmethoden
    private static void hello() {
        System.out.println("huhu");
    }

//    NestedClass
//    ---------------
    static class NestedClass {
//        Instanzvariable
        NestedClass[] subNestedArray;

        protected void foo() {
            SuperClass.hello();
        }

//        Instanzmethoden
        protected int add(int a, int b) {
            return a + b;
        }
    }
//    --------------
    
//    Klassenmethoden
    public static void main(String[] args) {
//        SuperClass sup2 = new NestedClass();
    }
    
    public String toString() {
        return "SuperName: "+name+"\n"+"SuperGebJahr: "+gebJahr+"\n\n";
    }
}

sudden bloomBOT
heavy echo
#

this is the right one

heavy echo
# proven current `SubClass` is not a type of `SuperClass`, so it can't be assigned here ```java S...

do you know why sup=sub; has no effect?


public class Statisch {
    static int a = 5;
    int b = 3;

    static void methodeStatic() {
        System.out.println("static Statisch");
    }

    void methodeInstanz() {
        System.out.println("non-static Statisch");
    }

    static class Sub_Statisch extends Statisch {
        static void methodeStatic() {
            System.out.println("static Sub_Statisch");
        }
        
        void mehtodeInstanz() {
            System.out.println("non-static Sub_Statisch");
        }
    }

    public static void main(String[] args) {
//        a = 4;
//        b = 22;
//
//        Statisch s;
//        Sub_Statisch sub;
//
//        s = new Sub_Statisch();
//        sub = new Statisch();
        
        Statisch sup = new Statisch();
        Sub_Statisch sub=new Sub_Statisch();
        
        sup.methodeInstanz();
        sup.methodeStatic();
        
        sup=sub;
        
        sup.methodeInstanz();
        sup.methodeStatic();
        

    }
}

sudden bloomBOT
# heavy echo do you know why sup=sub; has no effect? ``` public class Statisch { static ...

Detected code, here are some useful tools:

Formatted code
public class Statisch {
  static int a = 5;
  int b = 3;
  static void methodeStatic() {
    System.out.println("static Statisch");
  }
  void methodeInstanz() {
    System.out.println("non-static Statisch");
  }
  static class Sub_Statisch extends Statisch {
    static void methodeStatic() {
      System.out.println("static Sub_Statisch");
    }
    void mehtodeInstanz() {
      System.out.println("non-static Sub_Statisch");
    }
  }
  public static void main(String[] args) {
    //        a = 4;
    //        b = 22;
    //
    //        Statisch s;
    //        Sub_Statisch sub;
    //
    //        s = new Sub_Statisch();
    //        sub = new Statisch();
    Statisch sup = new Statisch();
    Sub_Statisch sub = new Sub_Statisch();
    sup.methodeInstanz();
    sup.methodeStatic();
    sup = sub;
    sup.methodeInstanz();
    sup.methodeStatic();
  }
}
heavy echo
#

zabuuuuuuu

blissful aspen
#

and what did u expect?

heavy echo
#

mehtodeInstanz

#

this was spelled wrong-.-

#

the correct output is

non-static Statisch
static Statisch
non-static Sub_Statisch
static Statisch
sudden bloomBOT
blissful aspen
#

static methods are not resolved via instances but via classes

#

sup.methodStatic() is, at compile-time, replaced by Statisch.methodStatic()

#

and stays like that forever

#

which is also why all IDEs emit warnings when u write instance.staticMethod()

#

instead of Class.staticMethod()

heavy echo
#

ye thats what i realised

#

static variables are bound to the static methods of its type doesn't matter if the pointer changes ?

blissful aspen
#

its about method calls

#

static things belong to classes

#

not to instances

heavy echo
#

sup is an instance of Statisch ?

blissful aspen
#

it doesnt matter whats inside the variable

#

its a pitty that java even allows writing variable.staticThing()

#

cause its always immediately replaced by

#

ClassOfVariableItself.staticThing()

#

which is why all IDEs give u a yellow warning if u do it

#

u should instead write Statisch.methodeStatic()

heavy echo
#

i do get warning

The static method methodeStatic() from the type Statisch should be accessed in a static way
blissful aspen
#

yeah. so if u follow this, u will never run into this confusion

heavy echo
#

this feels like an error somehow

blissful aspen
#

also, u should use @Override when u intent to override a method

#

then java would also be able to tell u immediately that u cant override static methods since they are not part of instances

#

and hence also not part of inheritance

#

so if u follow proper conventions, these issues cant even happen

heavy echo
#

sup.methodeInstanz(); //overwritten

so this is correct?

blissful aspen
#

what do u mean?

#

i proposed to add the override annotation to the method definition

#

and to access static methods via the class name

heavy echo
#
        @Override
        void methodeInstanz() {
            System.out.println("non-static Sub_Statisch");
        }

i mean that if override happens here ?

sudden bloomBOT
heavy echo
#

Gemini told me, that this isn't an override

In the corrected code, the line sup.methodeInstanz() might have printed something specific to Sub_Statisch because the typo fix allowed Sub_Statisch to define its own methodeInstanz() method. However, this wasn't technically an override. It was a separate method defined within Sub_Statisch that happened to have the same name.
heavy echo
#

why is java allowing objects to access static methods lol

#

this feels so wrong

edgy badge
#

why not?

#

method's main purpose is to be a reusable piece of code

#

and static methods are not bound to any object

#

so they are pure reusable pieces of code

blissful aspen
#

not sure who "Gemini" is. but ur methodeInstanz is an override

#

methodeStatic isnt, cause its static.

blissful aspen
#

foo.staticMethod()

#

not the fact that an object is allowed to call static methods, thats okay

heavy echo
#

okay

#

does this logic also apply to variables ?

#

because appearantly it doesn't

#

public class Statisch {
    static int a = 5;
    int b = 3;

    static void methodeStatic() {
        System.out.println("static Statisch");
    }

    void methodeInstanz() {
        System.out.println("non-static Statisch");
    }

    static class Sub_Statisch extends Statisch {
        static int a=10;
        int b=5;
//        no override because static methods are Class-Bound
        static void methodeStatic() {
            System.out.println("static Sub_Statisch");
        }
        @Override
        void methodeInstanz() {
            System.out.println("non-static Sub_Statisch");
        }
        
        void methodeInstanzSuper() {
            super.methodeInstanz();
        }
        
        void methodeStaticSuper() {
            super.methodeStatic();
        }
    }

    public static void main(String[] args) {
//        a = 4;
//        b = 22;
//
//        Statisch s;
//        Sub_Statisch sub;
//
//        s = new Sub_Statisch();
//        sub = new Statisch();
        
        Statisch sup = new Statisch();
        Sub_Statisch sub=new Sub_Statisch();
        
//        sup.methodeInstanz();
//        sup.methodeStatic();
//        
        sup=sub; // sup now points to sub
//        
        sup.methodeInstanz(); //overwritten
        sup.methodeStatic(); // *sup: the type of sup is still Statisch !!! it is always replaced by ClassOfVariableItself.staticThing()
//        Statisch.methodeStatic(); // sup.methodeStatic is converted to this
        
//        sub.methodeInstanz();
//        sub.methodeStatic();
//        sub.methodeInstanzSuper();
//        sub.methodeStaticSuper();

        System.out.println(sup.a); //pointer changes (sup=sub) do not affect variables but only methods ?!?
        System.out.println(sup.b); //pointer changes (sup=sub)do not affect variables but only methods ?!?

    }
}


#

sup.a and sup.b even though i did sup=sub

#

is still outputting the variables of the superclass

#

alteast for the instance variable

#

b

#

b should be 5 ?

#

sup=sub has an affect on methods

#

the non-static method is correctly overwritten

#
non-static Sub_Statisch
static Statisch
5
3

sudden bloomBOT
# heavy echo ``` public class Statisch { static int a = 5; int b = 3; static vo...

Detected code, here are some useful tools:

Formatted code
public class Statisch {
  static int a = 5;
  int b = 3;
  static void methodeStatic() {
    System.out.println("static Statisch");
  }
  void methodeInstanz() {
    System.out.println("non-static Statisch");
  }
  static class Sub_Statisch extends Statisch {
    static int a = 10;
    int b = 5;
    //        no override because static methods are Class-Bound
    static void methodeStatic() {
      System.out.println("static Sub_Statisch");
    }
    @Override
    void methodeInstanz() {
      System.out.println("non-static Sub_Statisch");
    }
    void methodeInstanzSuper() {
      super .methodeInstanz();
    }
    void methodeStaticSuper() {
      super .methodeStatic();
    }
  }
  public static void main(String[] args) {
    //        a = 4;
    //        b = 22;
    //
    //        Statisch s;
    //        Sub_Statisch sub;
    //
    //        s = new Sub_Statisch();
    //        sub = new Statisch();
    Statisch sup = new Statisch();
    Sub_Statisch sub = new Sub_Statisch();
    //        sup.methodeInstanz();
    //        sup.methodeStatic();
    //        
    sup = sub;
    // sup now points to sub
    //        
    sup.methodeInstanz();
    //overwritten
    sup.methodeStatic();
    // *sup: the type of sup is still Statisch !!! it is always replaced by ClassOfVariableItself.staticThing()
    //        Statisch.methodeStatic(); // sup.methodeStatic is converted to this
    //        sub.methodeInstanz();
    //        sub.methodeStatic();
    //        sub.methodeInstanzSuper();
    //        sub.methodeStaticSuper();
    System.out.println(sup.a);
    //pointer changes (sup=sub) do not affect variables but only methods ?!?
    System.out.println(sup.b);
    //pointer changes (sup=sub)do not affect variables but only methods ?!?
  }
}
blissful aspen
#

it also stands for variables

#

sup.a is immediately replaced by the compiler with Statisch.a and u get a warning for not writing it like that

#

b is not static. so what we were talking about doesnt apply for it

#

for b, u have whats called variable-shadowing

heavy echo
#

what is that?

#

why is b=5 not printed?

blissful aspen
#

uve introduced a new variable with the same name b

#

so ur instance of Sub_Statisch now has two variables named b

#

and both are visible cause u declared them (implicitly) public

#

this situation is btw very niche and wouldnt happen in normal coding

#

if ur using a proper IDE like intellij it should also give u a warning here

heavy echo
#

eclipse doesnt warn me>_>

#

but u said nichee

#

so i think im overthinking again

#

so with instance methods is overriding and with primitive types that aren't static its shadowing?

#

means both exist but the current variable the reference is pointing to shadows the one behind

#

that means

#

if a subclass inherits a variabl of super and also implement the same, it has 2 variables with same name ?

#

and sup uses the variable of the static type ?

edgy badge
#

static things are not part of inheritance

#

you can declare a field with the same name, but you're gonna end up with 2 fields

heavy echo
blissful aspen
blissful aspen
#

ur example is really difficult to work with cause it has all the names kinda wrong

#

for example a class named Static. that makes little sense terminology-wise

#

if stuff is confusing to u, u should come up with proper examples

#

like Animal and Dog

#

its also a bit difficult to follow ur thoughts if ur not explicitly naming what ur talking about

#

please be a bit more precise

#

im not really sure what is unclear to u still at the moment

heavy echo
#

okay i change the names

blissful aspen
#
class Animal {
  String name;
}
class Dog extends Animal {
  String name;
}

when u now create a dog new Dog(), it has 2 name variables

#

any animal already has a name. so Dog, being an Animal, gets that String name from its Animal-base

#

and then decides to create another one itself

#

so it ends up having two fields with the same name

#

and since both are public (or package private in this case), people from outside can access them

heavy echo
#

if i do

class Animal {
  String name;
}
class Dog extends Animal {
  String name;
}
Animal animal = new Animal();
Dog dog = new Dog();

dog=animal;

System.out.println(dog.name);

}```
sudden bloomBOT
blissful aspen
#

ull get the name of the type from the variable

#

not the instance behind the variable

#

new Dog().name is dogs

#

((Animal) new Dog()).name is animals

#
class Animal {
    String name = "Animal";
}
class Dog extends Animal {
    String name = "Dog";
}

public static void main(String[] args) {
    Dog dog = new Dog();
    Animal asAnimal = dog;
    System.out.println(dog.name); // Dog
    System.out.println(asAnimal.name); // Animal
}
sudden bloomBOT
#

@heavy echo

Your question has been closed due to inactivity.

If it was not resolved yet, feel free to just post a message below
to reopen it, or create a new thread.

Note that usually the reason for nobody calling back is that your
question may have been not well asked and hence no one felt confident
enough answering.

When you reopen the thread, try to use your time to improve the quality
of the question by elaborating, providing details, context, all relevant code
snippets, any errors you are getting, concrete examples and perhaps also some
screenshots. Share your attempt, explain the expected results and compare
them to the current results.

Also try to make the information easily accessible by sharing code
or assignment descriptions directly on Discord, not behind a link or
PDF-file; provide some guidance for long code snippets and ensure
the code is well formatted and has syntax highlighting. Kindly read through
https://stackoverflow.com/help/how-to-ask for more.

With enough info, someone knows the answer for sure 👍

heavy echo
#

i have a question left

steel veldt
heavy echo
#

hmm

#

its somehow difficult when i have many classes

cosmic mica
#

Enes her gün görüyorum seni, başarılar.

steel veldt
#

think in terms of layers. you have the concrete types: Pig, Dog, Cat

then you have a layer of abstraction: Animal. that abstracts all the concrete animals, and can include others (like Bird)

steel veldt
#

above that may be another layer of abstraction. LivingThing. that would include Animal, but also other things like Human and Plant

heavy echo
#

i have 3 classes,
"Immortal beings" being the superclass of mage and elben

#

Mages can heal but its not implemented in the super class:

and it says i can only solve this, when i want to use the heal method with casting like this:

((Magier) uw[1]).heilt(sw[0]);
steel veldt
#

thats because you arent using abstraction properly. you are given an abstraction like Animal, but you need a more specific type

#

sometimes you need the most-specific type. if you had a DogPark object, you'd wanna use the Dog type to access all the dog-specific stuff

#

in your case, you were given an abstract type, but you needed a concrete type. so you casted it

heavy echo
#

immortal being is indeed abstract

#

i made arrays like this:

    SterblicheWesen sw[]= {    new Hobbit("Hobbit",20), 
                            new Ork("Ork",30), 
                            new Zwerg("Zwerg",20)
                            };
    
    UnsterblicheWesen uw[]= {    new Elbe("Elbe",20), 
                                new Magier("Magier",20), 
                                };
sudden bloomBOT
steel veldt
#

you use abstractions where concrete information is not needed. in your case, you needed concrete info

#

DogPark? use dog, its expected for dogs to be used. PetCrate? well that can accept any kind of pet/animal

#

so instead of using Dog there, it would be better to use Animal, so the crate can support any animal. the crate doesnt need access to any concrete info

#

but DogPark does

heavy echo
#

is casting a valid and good choice then ?

steel veldt
#

if you have no control over the design, then yes, that would be the solution

#

otherwise, you should rethink your design

heavy echo
#

i only want mages to heal

#

but Mages and Eleben extend of the same superclass

#

the "wridVerwundet" method for example (taking dmg) is implemented in "Not imortal beings" but overwritten in their subclasses

#
    void wirdVerwundet(int dmg) {
        lebenserwartung -= dmg;
        System.out.println("Lebenserwartung von "+this.name+
                            " um "+dmg+" gesenkt auf "+this.lebenserwartung+"\n");
    }```
sudden bloomBOT
heavy echo
#

and so this works ?```
sw[0].wirdVerwundet(30)

#

without casting