Answer the question
In order to leave comments, you need to log in
Working with objects in java?
I'm trying to figure out how to create objects. There is a certain class A to create an object, we write A a1 = new A (). It seems to be simple. Then class B appears which inherits from class A. What does this object creation mean: A a2 = new B();
Why are the class names at the beginning and end different and what does this mean?
There is also this code:
class A{
int q = 33;
int sum(int a,int b){
return a+b;
}
}
class B extends A{
int q = 32;
int sum(int a, int b) {
return a-b;
}
}
public class beginner {
public static void main(String[] args) {
A a = new B();
System.out.println(a.sum(1,2));
System.out.println(a.q);
}
}
Answer the question
In order to leave comments, you need to log in
1. A a2 = new B();
means that you put the child class object into the parent class variable . This is possible and often necessary when you do not know exactly which of the heirs will be used or you want to abstract from a specific implementation.
2. a.sum(1,2)
calls the method overridden in the child class. Because it doesn't have a private modifier, it works.
3. When aq is called, the class variable A is called because the fields are not redefined.
I advise you to read about the OOP base: inheritance. polymorphism and encapsulation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question