how does base class know about sub class method? - java

public class BaseClass {
private String className;
public BaseClass() {
className = "[BaseClass]";
}
public void executeAB() {
System.out.println(className + " executingAB()");
executeA();
executeB();
}
public void executeA() {
System.out.println(this.className + " executingA()");
}
public void executeB() {
System.out.println(this.className + " executingB()");
}
}
public class SubClass extends BaseClass {
private String className;
public SubClass() {
this.className = "[SubClass]";
}
public void executeA() {
System.out.println(className + " executingA()");
}
public void executeC() {
System.out.println(className + " executingC()");
}
public static void main(String[] args) {
BaseClass t = new SubClass();
t.executeAB();
// t.executeC();
}
}
In above case , Calling t.executeAB() results in output:
[BaseClass] executingAB()
[SubClass] executingA()
[BaseClass] executingB()
My Question is:
How does BaseClass know about excuteA() method from SubClass, while at the same time t.executeC() call is not possible because BaseClass is not aware of executeC().

You have a misunderstanding of what you should be doing in inheritance. extends is a reserved word that was wisely chosen. The point of B extending A is to say that B is a subset of A with additional attributes. You're not supposed to redefine x in B; A should be handling x. You should have not className declared in both classes.
As for your example:
BaseClass t = new SubClass();
Calls the constructor for SubClass, which sets className of SubClass to [SubClass]. The super contructor is also called, and className in BaseClass is set to [BaseClass].
t.executeAB();
Prints the className for BaseClass which is [BaseClass] and then calls:
executeA();
executeB();
executeA() is a called from SubClass, since t is a SubClass and it's defined, so we get [SubClass] and finally, executeB() is called from BaseClass so again, we get [BaseClass]. As for why you can't call:
t.executeC()
Despite using the constructor for SubClass, t is a BaseClass. According to the principles of OOP, it makes sense that you can't call t.executeC(), since it is not defined for BaseClass.

You're defining your variable as BaseClass t = new SubClass(); which means you allow space for a different subclass to instantiate. However, in order for this to be possible without breaking existing code, you can only use methods that are defined in the baseclass.

Related

Inheritance constructor calling result

There are two classes. One inherited from the other one. Test results surprise me
since I called the child class constructor and its method. However I do not call the super class constructor like this new Cougar().go();. But output shows the the super class constructor is called. Could you explain me why this happens?
public class Feline {
public String type = "f";
public Feline() {
System.out.println("feline");
}
}
public class Cougar extends Feline {
public Cougar() {
System.out.println("cougar");
}
public static void main(String[] args) {
new Cougar().go();
}
private void go() {
type = "c";
System.out.println(this.type + " " + super.type);
}
}
Output: feline
cougar
c c
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
The constructor of the superclass is always invoked. You can call the desired constructor of your superclass using "super()" in the first line of your child class constructor.
For example:
public class Feline {
public Feline() {
System.out.println("Feline");
}
public Feline(String type) {
System.out.println(type);
}
...
}
public class Cougar extends Feline{
public Cougar() {
super("Cougar");
}
...
}
It is Because of line
new Cougar().go();
Inside the "go" method you have redefined the variable "type".
I hope it is making sense.
When we invoke child class constructor,the java compiler automatically calls super class
constructor.If it is not present in super class,we will get compile time error.
If Object is the super class of our class then no issue since Object contains no-arg constructor.
Reason- The reason to have super constructor called is that if super class could have private fields which need to be initialized by its constructor.
Refer this link for more info.
When you call parameter-less constructor of the derived class the run-time automatically calls the parameter-less base class constructor before executing the derived class constructor. Because of this behavior you see feline cougar as first two string in your output.
Now for the 'c c' part of the output, you are not defining new String type variable in your Cougar class. You are using the same 'type' variable if the super class in go() method/function and setting it to "c". This is the reason you are getting 'c c' in the output.
Make Cougar as below. The syntax is C#.
public class Cougar : Feline
{
public String type = "c";
public Cougar()
{
Console.Write("cougar ");
}
static void Main(String[] args)
{
new Cougar().go();
}
private void go()
{
Console.Write(this.type + " " + base.type);
}
}

Can a private method in super class be overridden in the sub-class?

Can private methods be overridden in Java?
If no, then how does the following code work?
class Base{
private void func(){
System.out.println("In Base Class func method !!");
};
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("In Derived Class func method");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func();
}
}
No, you are not overriding it. You can check by trying to mark it with #Override, or by trying to make a call to super.func();. Both won't work; they throw compiler errors.
Furthermore, check this out:
class Base {
private void func(){
System.out.println("In base func method");
};
public void func2() {
System.out.println("func2");
func();
}
}
class Derived extends Base {
public void func(){ // Is this an overriding method?
System.out.println("In Derived Class func method");
}
}
class InheritDemo {
public static void main(String [] args) {
Derived D = new Derived();
D.func2();
}
}
It will print:
func2
In base func method
When you change func() in Base to public, then it will be an override, and the output will change to:
func2
In Derived Class func method
No, a private method cannot be overridden because the subclass doesn't inherit its parent's private members. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class. There is no way an overriding method would be banned from accessing the method it is overriding, but this would precisely be the case here.
No, it is not. You can mark an override just to make sure like this:
#Override
public void func(){
System.out.println("In Derived Class func method");
}
And in this case it would be a compiler error.
You are not overriding. You cannot override private members, you are merely defining a new method in Derived. Derived has no knowledge Base's implementation of func() since its declared as private. You won't get a compiler error when you define func() in Derived but that is because Derived does not know Base has an implementation of func(). To be clear: it would be incorrect to say you are overriding Base's implementation of func().
In addition to the already correct answer, consider this:
public class Private {
static class A {
public void doStuff() {
System.out.println(getStuff());
}
private String getStuff() {
return "A";
}
}
static class B extends A {
public String getStuff() {
return "B";
}
}
public static void main(String[] args) {
A a = new A();
a.doStuff();
a = new B();
a.doStuff();
B b = new B();
b.doStuff();
}
}
This will print
A
A
A
although B "overrides" getStuff(). As implementation of doStuff() is fixed to calling A#getStuff(), no polymorphism will be triggered.
Nope because if you do something like Base b = new Derived(); you still won't be able to call b.func(). What you're doing is called "hiding".
Since the method is private it is not visible to the other classes.Hence the derived class does not inherit this method.
So this is not the case of overriding
Method hiding will be happening here instead of overriding. like what happens in case of static.
Actually,you are not overriding.Before Java5
an overridden method's return type must match with parent class's method.
But Java 5 introduced a new facility called covariant return type.You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
you can follow this thread :Can overridden methods differ in return type?
The private member of the base class cannot be access by anyone outside of the class and cannot be overridden. The function in the derive class is an independent function that can be access by anywhere.
The code would run the function in the derived class
A private method can never be over ridden. It is always hidden.
In your example - Derived class has one parent class private method and has its own function func. Both are different, and the func is not over ridden. Its a separate independent function.
If you create a new function in parent class calling parent class function, the parent func will be called, if parent class reference is used as opposed in the case of method over ridding
Note : An object defines the members which it has, and a reference defines which it can access
// Method Over ridding case
class Base{
public void func(){
System.out.println("Parent class");
};
public void func1(){
func();
}
}
class Derived extends Base{
public void func(){
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1(); // Prints Derived class - no matter parent reference is calling,as there as method is overridden - Check func1() is in parent class, but id doesn't call parent class func() as the compiler finds a func() method over ridden in derived class
}
}
// Method Hidding case - Private and static methods case
class Base{
private void func(){
System.out.println("Parent class");
};
public void func1(){
func()
}
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1();
// Prints Parent class - the reason is we are using the parent class reference, so compiler is looking for func() and it founds that there is one private class method which is available and is not over ridden, so it will call it. Caution - this won't happen if called using derived class reference.
b.func();
// this prints the Derived class - the compiler is looking func(), as Derived class has only one func() that it is implementing, so it will call that function.
}
}
Read comments in the below code snippet to find the answer.
Sources:
Definition reference:
Credits for the source code example(reference) from the book - "OCA Oracle Certified Associate Java SE 8 Programmer Study Guide Exam 1Z0-808 Book" from 'Jeanne Boyarsky' and 'Scott Selikoff'.
public class Deer {
public Deer() { System.out.print("Deer"); }
public Deer(int age) { System.out.print("DeerAge"); }
private boolean hasHorns() { return false; }
public static void main(String[] args) {
Deer deer = new Reindeer(5);
System.out.println(","+deer.hasHorns());// false is printed.
}
}
class Reindeer extends Deer {
public Reindeer(int age) { System.out.print("Reindeer"); }
private boolean hasHorns() { return true; } // Overriding possible, but is of no use in the below context.
// Below code is added by me for illustration purpose
public static void main(String[] args) {
Deer deer = new Reindeer(5);
//Below line gives compilation error.
//System.out.println(","+deer.hasHorns());
}
}

What's the difference between this and super keywords in java?

Check my coolMethod, babes:
package zoo;
public class Zoo {
public String coolMethod() {
return "Wow baby!";
}
}
My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.
package zoo;
public class Moo extends Zoo {
public void useAZoo(){
Zoo z = new Zoo();
System.out.println("A Zoo says: "+ z.coolMethod());
}
public void useMyCoolMethod(){
System.out.println("My cool method says: " + super.coolMethod());
}
public void useMyCoolMethodAgain(){
System.out.println("My cool method says: " + this.coolMethod()+ " (again)");
}
public void inheritMyMethod(){
System.out.println("My inhertied method says: " + coolMethod());
}
}
And my main, that calls my Moo class functionalities.
package javacert1;
import zoo.Moo;
public class Main {
public static void main(String[] args) {
Moo moo = new Moo();
moo.useAZoo();
moo.useMyCoolMethod();
moo.useMyCoolMethodAgain();
moo.inheritMyMethod();
}
}
As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?
Since you have only one coolMethod, it is called in each case, regardless of qualifiers. However, if you override your method in Moo e.g. like this
public class Moo extends Zoo {
public String coolMethod() {
return "Yeah dude!";
}
// the rest is the same as above...
}
you will notice the difference between the calls to coolMethod() and this.coolMethod() versus the call to super.coolMethod().
this can be pointing to current object
super can be used for accessing Super class metods & variables
this() can be used to invoke a constructor of the same class
super() can be used to invoke a super class constructor
Difference with examples
Cool example, overmann :)
Here is another example ... has 2 source files - LevelSub.java which extends LevelSup.java
Save the 2 in some folder, compile using "javac LevelSub.java" (compiler will know from "extends" that it has to compile "LevelSup.java", too), and run "java LevelSub". The comments in the source code should tell you the difference.
this and super are used when there is a name clash for variables or methods (e.g., same name is used in super/sub classes or in a method body, or you want to call a method from the superclass that has been overridden). "this" refers to the current object instance and "super" refers to the one it is inheriting from. For no name clashes, the this or super prefix are redundant.
public class LevelSub extends LevelSup {
protected String myName;
public LevelSub (String myName) {
super ("SuperClass");
this.myName = myName; // sets up instance variable
}
public void print () {
System.out.println ("Hi, this is " + myName); // refers to this.myName
System.out.println ("I am inherited from " + super.myName);
System.out.println ("also known as " + defaultName); // gets from superclass
super.print(); // overridden method of superclass
}
public static void main (String[] args) {
new LevelSub("SubClass").print();
}}
and the other source ...
public class LevelSup {
// cannot be private if accessed by subclass
protected String myName, defaultName = "TopLevel";
public LevelSup (String name) {
myName = name; // this not required, no name clash
}
// cannot be private if accessed by subclass
public void print () {
System.out.println ("Hi, this is " + myName);
}
}
You are not overriding the coolMethod and you are inheriting it.
As a result it calls the same method.
Override coolMethod and see what happens.
super will call the method of base.
this will call method in this object
"this" refers to the object you're in. "super" refers to the parent of this object. I think you're missing the difference because of some other things you have going on.
For example, this code
public class Zoo {
public String coolMethod() {
return "Wow baby!";
}
}
public class Moo extends Zoo {
public void useAZoo(){
Zoo z = new Zoo();
System.out.println("A Zoo says: "+ z.coolMethod());
}
public void useMyCoolMethod(){
System.out.println("My cool method says: " + super.coolMethod());
}
public void useMyCoolMethodAgain(){
System.out.println("My cool method says: " + this.coolMethod()+ " (again)");
}
public void inheritMyMethod(){
System.out.println("My inhertied method says: " + coolMethod());
}
}
The method "coolMethod" is defined in Zoo, but it's a public method so it is naturally inherited by Moo. So, when you're within your Moo class and you call this.coolMethod or super.coolMethod, you end up with exactly the same thing. Where things get far more interesting is if you override the coolMethod in your subclass, like this:
public class Zoo {
public String coolMethod() {
return "Wow baby!";
}
}
public class Moo extends Zoo {
#Override
public String coolMethod() {
return "Moo baby!";
}
public void doIt() {
System.out.println("Using super: " + super.coolMethod());
System.out.println("Using this: " + this.coolMethod());
}
}
Try executing "doIt" in that case and I think you'll see the difference much easier.
In this case, they will do nothing different.
However, if you were to override coolMethod in the Moo class, the call to the super version will call the version in the Zoo class, but all the other versions will call the new overridden one.
To see the difference, overwrite the coolMethod in your subclass Moo:
public String coolMethod() {
return "Moo baby!";
}
I suggest you, to create a coolMethod in your Moo class, that print something different, from the one in the Zoo class

super() in Java

Is super() used to call the parent constructor?
Please explain super().
super() calls the parent constructor with no arguments.
It can be used also with arguments. I.e. super(argument1) and it will call the constructor that accepts 1 parameter of the type of argument1 (if exists).
Also it can be used to call methods from the parent. I.e. super.aMethod()
More info and tutorial here
Some facts:
super() is used to call the immediate parent.
super() can be used with instance members, i.e., instance variables and instance methods.
super() can be used within a constructor to call the constructor of the parent class.
OK, now let’s practically implement these points of super().
Check out the difference between program 1 and 2. Here, program 2 proofs our first statement of super() in Java.
Program 1
class Base
{
int a = 100;
}
class Sup1 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup1().Show();
}
}
Output:
200
200
Now check out program 2 and try to figure out the main difference.
Program 2
class Base
{
int a = 100;
}
class Sup2 extends Base
{
int a = 200;
void Show()
{
System.out.println(super.a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup2().Show();
}
}
Output:
100
200
In program 1, the output was only of the derived class. It couldn't print the variable of neither the base class nor the parent class. But in program 2, we used super() with variable a while printing its output, and instead of printing the value of variable a of the derived class, it printed the value of variable a of the base class. So it proves that super() is used to call the immediate parent.
OK, now check out the difference between program 3 and program 4.
Program 3
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup3 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup3().Show();
}
}
Output:
200
Here the output is 200. When we called Show(), the Show() function of the derived class was called. But what should we do if we want to call the Show() function of the parent class? Check out program 4 for the solution.
Program 4
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup4 extends Base
{
int a = 200;
void Show()
{
super.Show();
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup4().Show();
}
}
Output:
100
200
Here we are getting two outputs, 100 and 200. When the Show() function of the derived class is invoked, it first calls the Show() function of the parent class, because inside the Show() function of the derived class, we called the Show() function of the parent class by putting the super keyword before the function name.
Source article: Java: Calling super()
Yes. super(...) will invoke the constructor of the super-class.
Illustration:
Stand alone example:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints:
Constructing an animal: From Dog constructor
Constructing a dog.
Is super() is used to call the parent constructor?
Yes.
Pls explain about Super().
super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.
Here's the official tutorial
Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.
class Explicit() {
Explicit() {
super();
}
}
class Implicit {
Implicit() {
}
}
Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)
There is also a super keyword, that you can use in methods to invoke a method of the superclass
A quick google for "Java super" results in this
That is correct. Super is used to call the parent constructor. So suppose you have a code block like so
class A{
int n;
public A(int x){
n = x;
}
}
class B extends A{
int m;
public B(int x, int y){
super(x);
m = y;
}
}
Then you can assign a value to the member variable n.
I have seen all the answers. But everyone forgot to mention one very important point:
super() should be called or used in the first line of the constructor.
Just super(); alone will call the default constructor, if it exists of a class's superclass. But you must explicitly write the default constructor yourself. If you don't a Java will generate one for you with no implementations, save super(); , referring to the universal Superclass Object, and you can't call it in a subclass.
public class Alien{
public Alien(){ //Default constructor is written out by user
/** Implementation not shown…**/
}
}
public class WeirdAlien extends Alien{
public WeirdAlien(){
super(); //calls the default constructor in Alien.
}
}
For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:
public class DeveloperSteps extends ScenarioSteps {
public DeveloperSteps(Pages pages) {
super(pages);
}........
I would like to share with codes whatever I understood.
The super keyword in java is a reference variable that is used to refer parent class objects. It is majorly used in the following contexts:-
1. Use of super with variables:
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:-
Maximum Speed: 120
Use of super with methods:
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
Output:-
This is student class
This is person class
3. Use of super with constructors:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
/* Driver program to test*/
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:-
Person class Constructor
Student class Constructor
What can we use SUPER for?
Accessing Superclass Members
If your method overrides some of its superclass's methods, you can invoke the overridden method through the use of the keyword super like super.methodName();
Invoking Superclass Constructors
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Look at the code below:
class Creature {
public Creature() {
system.out.println("Creature non argument constructor.");
}
}
class Animal extends Creature {
public Animal (String name) {
System.out.println("Animal one argument constructor");
}
public Animal (Stirng name,int age) {
this(name);
system.out.println("Animal two arguments constructor");
}
}
class Wolf extends Animal {
public Wolf() {
super("tigerwang",33);
system.out.println("Wolf non argument constructor");
}
public static void main(string[] args) {
new Wolf();
}
}
When creating an object,the JVM always first execute the constructor in the class
of the top layer in the inheritance tree.And then all the way down the inheritance tree.The
reason why this is possible to happen is that the Java compiler automatically inserts a call
to the no-argument constructor of the superclass.If there's no non-argument constructor
in the superclass and the subclass doesn't explicitly say which of the constructor is to
be executed in the superclass,you'll get a compile-time error.
In the above code,if we want to create a Wolf object successfully,the constructor of the
class has to be executed.And during that process,the two-argu-constructor in the Animal
class is invoked.Simultaneously,it explicitly invokes the one-argu-constructor in the same
class and the one-argu-constructor implicitly invokes the non-argu-constructor in the Creature
class and the non-argu-constructor again implicitly invokes the empty constructor in the Object
class.
Constructors
In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class :
public MyClass(int a) {
this(a, 5); // Here, I call another one of this class's constructors.
}
public MyClass(int a, int b) {
super(a, b); // Then, I call one of the superclass's constructors.
}
super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors.
Methods
In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class :
public String toString() {
int hp = this.hitpoints(); // Calls the hitpoints method in this class
// for this object.
String name = super.name(); // Calls the name method in the superclass
// for this object.
return "[" + name + ": " + hp + " HP]";
}
super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.
The super keyword can be used to call the superclass constructor and to refer to a member of the superclass
When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.
At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.
public class Box {
int width;
int height;
int depth;
Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
public static void main(String[] args){
HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
}
}
class HeavyBox extends Box {
int weight;
HeavyBox(int w, int h, int d, int m) {
//call the superclass constructor
super(w, h, d);
weight = m;
}
}
super is a keyword. It is used inside a sub-class method definition to call a method defined in the superclass. Private methods of the superclass cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class.
Check here for further explanation.
As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.
This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .
If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.
Here is an example of this:
class A {
A() {
System.out.println("Constructor A");
}
}
class B extends A{
public B() {
System.out.println("Constructor B");
}
}
class C extends B{
public C() {
System.out.println("Constructor C");
}
public static void main(String[] args) {
C c1 = new C();
}
}
The above would output:
Constructor A
Constructor B
Constructor C
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.
Usage of Java super Keyword
super can be used to refer to the immediate parent class instance variable.
super can be used to invoke the immediate parent class method.
super() can be used to invoke immediate parent class constructor.
There are a couple of other uses.
Referencing a default method of an inherited interface:
import java.util.Collection;
import java.util.stream.Stream;
public interface SkipFirstCollection<E> extends Collection<E> {
#Override
default Stream<E> stream() {
return Collection.super.stream().skip(1);
}
}
There is also a rarely used case where a qualified super is used to provide an outer instance to the superclass constructor when instantiating a static subclass:
public class OuterInstance {
public static class ClassA {
final String name;
public ClassA(String name) {
this.name = name;
}
public class ClassB {
public String getAName() {
return ClassA.this.name;
}
}
}
public static class ClassC extends ClassA.ClassB {
public ClassC(ClassA a) {
a.super();
}
}
public static void main(String[] args) {
final ClassA a = new ClassA("jeff");
final ClassC c = new ClassC(a);
System.out.println(c.getAName());
}
}
Then:
$ javac OuterInstance.java && java OuterInstance
jeff

Why access to filed and method differs in inherited class in Java?

class BaseClass {
protected int filed = 1;
public void method() {
System.out.println("+ BaseClass method");
}
}
class DerivedClass extends BaseClass {
private int filed = 2;
public void method() {
System.out.println("+ DerivedClass method");
}
public void accessFiled() {
System.out.println("DerivedClass: default filed = " + filed); // output 1
System.out.println("DerivedClass: upcasting filed = " + ((BaseClass)this).filed); // output 2
}
public void accessMethod() {
System.out.println("DerivedClass: default method");
method(); // output "+ DerivedClass method"
System.out.println("DerivedClass: upcasting method");
((BaseClass)this).method(); // expecting "+ BaseClass method" but "+ DerivedClass method"
}
}
Why the access to filed(data member) and method differs?Could you explain it to me on both language design and implementation details aspects?
thanks.
This happens because you can only override methods, not fields. In DerivedClass your hiding the variable filed declared in the BaseClass. An instance of DerivedClass really has 2 fields called filed and you can access both with the appropriate cast. It wouldn't make much sense being able to override fields... Only behavior.

Categories

Resources