I've been trying to teach myself inheritance using java, but I am really confused and it seems online youtube videos/looking at previous questions are not helping at all. I tried the practice problems on this website: http://javaconceptoftheday.com/java-inheritance-practice-coding-questions/ , but I am having trouble with questions 2, 3, and 7.
In question 2, since the constructor of object a is B(), why wouldn't it print class B's i value instead of class a's? Instead it prints class a's and I have no idea why.
In question 3, is the reason that the program prints 1 2 3 because there are no constructors and it's just the function? I know when you inherit from a class, you basically act as if all of its functions are in the subclass, so do you basically just pretend class C says:
System.out.println(1);
System.out.println(2);
System.out.println(3);?
In question 7, since the constructor is a C() constructor, why does it still go through the code in the constructor for class A and class B?
Thank you for any help you can give, inheritance is just one of the topics I did not cover in my intro to programming class so I'm trying to fill in all of the blanks before fall semester starts.
Code for question 2:
class A
{
int i = 10;
}
class B extends A
{
int i = 20;
}
public class MainClass
{
public static void main(String[] args)
{
A a = new B();
System.out.println(a.i);
}
}
Code for question 3:
class A
{
{
System.out.println(1);
}
}
class B extends A
{
{
System.out.println(2);
}
}
class C extends B
{
{
System.out.println(3);
}
}
public class MainClass
{
public static void main(String[] args)
{
C c = new C();
}
}
Code for question 7:
class A
{
public A()
{
System.out.println("Class A Constructor");
}
}
class B extends A
{
public B()
{
System.out.println("Class B Constructor");
}
}
class C extends B
{
public C()
{
System.out.println("Class C Constructor");
}
}
public class MainClass
{
public static void main(String[] args)
{
C c = new C();
}
}