#Inheritance
1 messages · Page 1 of 1 (latest)
<@&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>.
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."
Super
Nested -----> Sub Class
does it mean Sub Class of a nested class can manipulate super class of nested class
its about visibility
private means visible within the same class
that includes nested classes
where did you hear it?
This beginner Java tutorial describes fundamentals of programming in the Java programming language
class Outer {
private static void hello() { System.out.println("huhu"); }
static class Inner {
void foo() { Outer.hello(); }
}
}
now, a third class can write
its a about leakage
Outer.Inner inner = new Outer.Inner();
inner.foo();
and that will print huhu
but cant write
Outer.huhu();
directly
you mean Outer.hello()
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
that means a subclass of Inner , also inheritated Outer ?
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
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)
provided the nested class didnt define its interface properly
can Inner also do it ?
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
therefore, a nested class inherited by a subclass has indirect access to private members
y missed the last word that confused me "of the superclass"
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
so the point is about indirect access of subs from nested ?
through protected and below methods ?
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
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
like this
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 ?
t1.getClass().isInstance(object)
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
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
alathreon my fav java professor are you theree
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
yes it was labeled wrong
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";
}
}
Detected code, here are some useful tools:
this is the right one
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();
}
}
Detected code, here are some useful tools:
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();
}
}
zabuuuuuuu
mehtodeInstanz
this was spelled wrong-.-
the correct output is
non-static Statisch
static Statisch
non-static Sub_Statisch
static Statisch
Detected code, here are some useful tools:
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()
ye thats what i realised
static variables are bound to the static methods of its type doesn't matter if the pointer changes ?
sup is an instance of Statisch ?
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()
i do get warning
The static method methodeStatic() from the type Statisch should be accessed in a static way
yeah. so if u follow this, u will never run into this confusion
this feels like an error somehow
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
sup.methodeInstanz(); //overwritten
so this is correct?
what do u mean?
i proposed to add the override annotation to the method definition
and to access static methods via the class name
@Override
void methodeInstanz() {
System.out.println("non-static Sub_Statisch");
}
i mean that if override happens here ?
Detected code, here are some useful tools:
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.
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
if the method has the same signature (return type, name, argument list) and is non-static, its an override
not sure who "Gemini" is. but ur methodeInstanz is an override
methodeStatic isnt, cause its static.
the part thats "wrong" is accessing them through objects
foo.staticMethod()
not the fact that an object is allowed to call static methods, thats okay
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
Detected code, here are some useful tools:
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 ?!?
}
}
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
variable shadowing ?
what is that?
why is b=5 not printed?
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
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 ?
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
in my example, pointer assignment didn't do anything, so the first variable is always taken ?
has nothing to do with primitive or not
yes
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
okay i change the names
sup.b is unclear
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
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);
}```
Detected code, here are some useful tools:
Request failed: Too Many Requests. Too many sessions, try again later :(.
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
}
@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 👍
i have a question left
no need to announce, just post the question
Enes her gün görüyorum seni, başarılar.
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)
Please use English
above that may be another layer of abstraction. LivingThing. that would include Animal, but also other things like Human and Plant
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]);
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
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),
};
Detected code, here are some useful tools:
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
is casting a valid and good choice then ?
if you have no control over the design, then yes, that would be the solution
otherwise, you should rethink your design
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");
}```
Detected code, here are some useful tools: