I am a newbie in Java, and would like to understand more about inheritance. Suppose
class Vehicle{
public void move(){
System.out.println(“Vehicles can move”);
}
}
class MotorBike extends Vehicle{
public void move(){
System.out.println(“MotorBike can move and accelerate tool”);
}
}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move();
vh=new Vehicle();
vh.move();
}
}
When we do vh.move() in the 1st time it prints MotorBike can move and accelerate tool. Second time it prints Vehicles can move.
It can be called method overriding. Because we have same method name in two class.
But, if two classes have different method, then which method should be called? I want to say like that,
class Vehicle{
public void move(){
System.out.println(“Vehicles can move”);
}
}
class MotorBike extends Vehicle{
public void part(){
System.out.println(“MotorBike can move and accelerate tool”);
}
}
class Test{
public static void main(String[] args){
vehicle a = new vehicle();
Vehicle vh=new MotorBike();
}
}
In the first case vehicle a = new vehicle();it invoke move() and
What will be the second case? If I do `Vehicle vh=new MotorBike();
Which method should be called? move() or part()?
In the second case, even though you have defined an extra method part(), you can only call the move() method (which is inherited from Vehicle) because you have told the compiler that vh is a Vehicle (it doesn't know that it's a Motorbike)
Vehicle vh = new MotorBike(); // from now on, vh is a Vehicle - we don't know it's a MotorBike
vh.move(); // this is fine
vh.part(); // this will not compile
If you want to call the part() method then you have to define the variable as a MotorBike:
MotorBike vh = new MotorBike(); // now we know it's a MotorBike
vh.part(); // this is ok now
it can be called method overridding.becoz we have same method name in
two class.
Well, yes ... but what your code illustrates is that the same method invoked on two objects referenced by the same variable can exhibit different behavior (that is determined by their underlying type). Yes, this requires overloading, but the principle that has been demonstrated is polymorphism.
what will be the 2nd case?if i do Vehicle vh=new MotorBike(); which
method should be called? move() or part()??
In polymorphism, the most specific method in an object hierarchy gets invoked when that method is invoked on an object reference. Consider this example:
public class Parent {
public void emote() {
System.out.println("I'm the parent")'
}
public void parentMethod() { ... }
}
public class Child extends Parent {
#Override
public void emote() {
System.out.println("I'm the child");
}
public void childMethod() { ... }
}
Now consider the following test code:
public void test() {
Parent p1 = new Parent();
p1.emote(); // method invocation prints "I'm the parent"
Parent p2 = new Child();
p2.emote(); // prints "I'm the child"
}
Note that the p2 variable type does not determine the method that gets invoked when the emote() method is called. This is important to understant because a reference variable can point to an object of its own type ... or to any other object that is a subclass of the variable's type.
The method that is invoked is the most specific method that applies to the actual object that is referenced by the variable. In this case, the emote() method on the Child object itself is invoked.
Also, this is valid:
p2.parentMethod();
Even though p2 references a Child object, the Child class inherits the parentMethod() method from it and so the invocation works. These fail, though:
p1.childMethod();
p2.childMethod();
The Parent class does not know anything about the methods that any of its subclasses may define. It may not be intuitive why the second invocation should fail. Although p2 references a Child object, the Parent class does not have a childMethod() declaration. To make this work, we would need to cast p2 to the Child type:
((Child) p2).childMethod();
Related
Consider the code below :
abstract class AbstractClass {
abstract m1();
}
public class Test {
public static void main(String [] args) {
AbstractClass obj = new AbstractClass() {
#Override void m1() {
System.out.print("Instance of abstract class !");
}
};
obj.m1();
}
}
Now here is what I did not understand about this code.
I read that anonymous class creates the class with unknown name which extends the class whose reference is provided (here it is abstract AbstractClass).
Also I remember that we cannot implement the method of child class if the the object is having reference of parent class.
see block of code below
Parent obj = new Child();
obj.methodOfParent();
obj.methodOfChild(); //this gives error
Now here is my point if Anonymous Class extends its Parent Class whose reference is provided, then how can we call overriden methods of Parent Class from Anonymous Class?
I guess you just miss one point. Let me show you example:
class Parent {
public void methodOfParent() {}
public void methodOfParentToBeOverriden() {}
}
class Child extends Parent {
#Override public void methodOfParentToBeOverriden() {}
public void methodOfChild() {}
}
Parent obj = new Child();
obj.methodOfParent(); //this is OK
obj.methodOfParentToBeOverriden(); // this is OK too
obj.methodOfChild(); //this gives error
((Child)obj).methodOfChild(); //this is OK too here.
Please note that when you call obj.methodOfParentToBeOverriden() it will be called implementation from Child class. Independence did you cast this object to Parent type or not.
There is a difference between calling an overridden method of parent and calling a method of child. If a method is declared in class T, you can call it on a variable statically typed as T, regardless of where the method is actually implemented.
In your example, if obj.methodOfParent() happens to be a method override from Child, the method in Child will run, even though obj's static type is Parent.
Same mechanism is in play with anonymous classes: the reason that you are allowed to call obj.m1() is that m1() has been declared in the parent class.
When a class extends a class, we can use Super-class reference while assigning memory to the subclass object.
I have understood so far is that it is ok to do so, because a subclass inherits the data of its parent class, but it cannot access the members of the subclass because it is the just the reference, and hence does not know of what additions are done by the child class.
My question is when I included method hiding to the above concept, the superclass reference variable started to refer to the child's class function. Why is that ? Why it didnt call it's own method as it is supposed to ?
class A{
void show(){ System.out.print("CLass A. \n"); }
}
class B extends A{
void show(){System.out.print("Class B. \n"); }
}
class Main{
public static void main(String[] args){
A a= new A();
B b= new B();
a.show(); // prints Class A
b.show(); // prints Class B
A a1= new B();
a1.show(); // print Class B. why is this ? it should be Class A as per theory?
}
}
variables and methods are two different things. Variables stick to their types where as methods get executed run time based on the implementation type provided.
Polymorphism. Methods bind dynamically and choosen at run time. If you ovveride them implementation class, they get executed otherwise the implementation from type class gets execute.
When you write
A a1= new B();
Means that please call the implementations from the class B(which is on right side) which are from type A
You have to know about overriding concept in java.
From oracle documentation page regarding overriding:
Overriding and Hiding Methods
Instance Methods
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed.
But overriding is different from hiding.
Static Methods
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:
The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Example to understand:
public class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal");
}
}
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
output:
The static method in Animal
The instance method in Cat
It allways calls the method from the most specific class.
I have a parent class Shape and a subclass Rectangle, I have a method in parent class Shape called Output.
How can I call the parent class method Output in the children class?
The Parent Class
public class Shape {
public int edge;
public Shape(int Gedge) {
edge=Gedge;
}
public void Output() {
System.out.println("This shape has "+edge+" eges");
}
}
The Subclass:
public class Rectangle extends Shape {
public int edge, length, width;
public Rectangle(int Gedge, int Glength, int Gwidth) {
super (Gedge);
edge=Gedge;
length=Glength;
width=Gwidth;
}
public void Output1() {
//I want to call the parent class Method "Output" here.
System.out.println("The Area is "+length*width);
}
public static void main (String [] args) {
Rectangle A1=new Rectangle(4,3,5);
A1.Output1();
}
}
If I run this code now, the output is The Area is 15, but I want to call the Output method in Shape, so ideally it prints
This shape has 4 edges
The area is 15
Help is Appreciated. Thanks
Just call the method :
public void Output1()
{
Output();
System.out.println("The Area is "+length*width);
}
There's no need for the super keyword, since you are not calling a method of the base class that is overridden by your Output1 method. You are calling a different method.
I think in your example specifically shape must be interface(with method area() and (Rect,Square..) implementing it. Back to your question, because that is in your parent class Output is public you can do from child class this : super.Output();
As others have already answered the question (both call super.Output() or just call Output() are correct), I will attempt to give a little more clarity as to why both are correct (and it's mostly due to your naming conventions).
When you have a parent-child relationship between classes, like so:
class A {
public void doStuff(){
System.out.println("Doing A Stuff!");
}
}
class B extends A {
public void doStuff(){
System.out.println("Doing B Stuff!");
}
}
What you are doing is overriding the doStuff method. The behaviour will be as follows:
A a = new B(); // A is the parent type of a, B is the actual type.
a.doStuff(); // prints "Doing B stuff!"
When you override in Java, the method has to have the exact same name, parameters list (in the same order), and return type. So in your example Output1 is NOT an override of Output. This is why you actually can get away with calling Output() anywhere in your subclass, without the need for the 'super' keyword. If you were to refactor your code so that both methods had the same signature, then yes, the only way to call the behaviour of the parent class is to call super.Output() in the overriding method. In fact, if you then wrote your subclass B in the following way, the call to doStuff would be a recursive call and the method would recurse until you hit a stack overflow (hence, you need to use super.doStuff()):
class B extends A {
public void doStuff(){
doStuff(); // BAD CODE!! Use super.doStuff() here instead!
System.out.println("Doing B Stuff!");
}
}
Another way you could ensure you call the superclass's method is to instantiate the object with an actual type of the supertype, but then you lose all of the functionality of the subclass:
A a = new A(); //both parent type and actual type of a is A
a.doStuff(); // prints "Doing A stuff!" (can't print "Doing B Stuff!")
Also, as commented, you should check out this question which will point you in the direction of official Java style guidelines and conventions. Some quick things to note about your code is the lack of lower camel case for local variables (A1 should be a1) and methods (Output() should be output())
I'm confused about what it means to cast objects in Java.
Say you have...
Superclass variable = new Subclass object();
(Superclass variable).method();
What is happening here? Does the variable type change, or is it the object within the variable that changes? Very confused.
Have a look at this sample:
public class A {
//statements
}
public class B extends A {
public void foo() { }
}
A a=new B();
//To execute **foo()** method.
((B)a).foo();
Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()
The method will not accept grapes for example so you want to make sure that you're adding a banana to the basket.
So:
Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket(); ⇐ This is called casting
The example you are referring to is called Upcasting in java.
It creates a subclass object with a super class variable pointing to it.
The variable does not change, it is still the variable of the super class but it is pointing to the object of subclass.
For example lets say you have two classes Machine and Camera ; Camera is a subclass of Machine
class Machine{
public void start(){
System.out.println("Machine Started");
}
}
class Camera extends Machine{
public void start(){
System.out.println("Camera Started");
}
public void snap(){
System.out.println("Photo taken");
}
}
Machine machine1 = new Camera();
machine1.start();
If you execute the above statements it will create an instance of Camera class with a reference of Machine class pointing to it.So, now the output will be "Camera Started"
The variable is still a reference of Machine class. If you attempt machine1.snap(); the code will not compile
The takeaway here is all Cameras are Machines since Camera is a subclass of Machine but all Machines are not Cameras. So you can create an object of subclass and point it to a super class refrence but you cannot ask the super class reference to do all the functions of a subclass object( In our example machine1.snap() wont compile). The superclass reference has access to only the functions known to the superclass (In our example machine1.start()). You can not ask a machine reference to take a snap. :)
Sometimes you will like to receive as argument a Parent reference and inside you probably want to do something specific of a child.
abstract class Animal{
public abstract void move();
}
class Shark extends Animal{
public void move(){
swim();
}
public void swim(){}
public void bite(){}
}
class Dog extends Animal{
public void move(){
run();
}
public void run(){}
public void bark(){}
}
...
void somethingSpecific(Animal animal){
// Here you don't know and may don't care which animal enters
animal.move(); // You can call parent methods but you can't call bark or bite.
if(animal instanceof Shark){
Shark shark = (Shark)animal;
shark.bite(); // Now you can call bite!
}
//doSomethingSharky(animal); // You cannot call this method.
}
...
In above's method you can pass either Shark or Dog, but what if you have something like this:
void doSomethingSharky(Shark shark){
//Here you cannot receive an Animal reference
}
That method can only be called by passing shark references
So if you have an Animal (and it is deeply a Shark) you can call it like this:
Animal animal...
doSomethingSharky((Shark) animal)
Bottom line, you can use Parent references and it is usually better when you don't care about the implementation of the parent and use casting to use the Child as an specific object, it will be exactly the same object, but your reference know it, if you don't cast it, your reference will point to the same object but cannot be sure what kind of Animal would it be, therefore will only allow you to call known methods.
Superclass variable = new subclass object(); This just creates an object of type subclass, but assigns it to the type superclass. All the subclasses' data is created etc, but the variable cannot access the subclasses data/functions. In other words, you cannot call any methods or access data specific to the subclass, you can only access the superclasses stuff.
However, you can cast Superclassvariable to the Subclass and use its methods/data.
Lets say you have Class A as superclass and Class B subclass of A.
public class A {
public void printFromA(){
System.out.println("Inside A");
}
}
public class B extends A {
public void printFromB(){
System.out.println("Inside B");
}
}
public class MainClass {
public static void main(String []args){
A a = new B();
a.printFromA(); //this can be called without typecasting
((B)a).printFromB(); //the method printFromB needs to be typecast
}
}
In this example your superclass variable is telling the subclass object to implement the method of the superclass. This is the case of the java object type casting. Here the method() function is originally the method of the superclass but the superclass variable cannot access the other methods of the subclass object that are not present in the superclass.
For example you have Animal superclass and Cat subclass.Say your subclass has speak(); method.
class Animal{
public void walk(){
}
}
class Cat extends Animal{
#Override
public void walk(){
}
public void speak(){
}
public void main(String args[]){
Animal a=new Cat();
//a.speak(); Compile Error
// If you use speak method for "a" reference variable you should downcast. Like this:
((Cat)a).speak();
}
}
in some cases we can’t provide guarantee for the type of elements or objects present inside our collection or wise,
at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error.
Arrays are always type safe that is we can provide the guarantee for the type of elements present inside array.
to achieve type safety we have to use typecasting.
Casting is necessary to tell that you are calling a child and not a parent method. So it's ever downward. However if the method is already defined in the parent class and overriden in the child class, you don't any cast. Here an example:
class Parent{
void method(){ System.out.print("this is the parent"); }
}
class Child extends Parent{
#override
void method(){ System.out.print("this is the child"); }
}
...
Parent o = new Child();
o.method();
((Child)o).method();
The two method call will both print : "this is the child".
I have a parent class which has a method, in the child class I override that parent class's method. In a third class I make an object of child and by using that object I want call the method of parent class. Is it possible to call that parent class method ? If yes, then how?
If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.
public class PolyTest{
public static void main(String args[]){
new Child().foo();
}
}
class Parent{
public void foo(){
System.out.println("I'm the parent.");
}
}
class Child extends Parent{
#Override
public void foo(){
//super.foo();
System.out.println("I'm the child.");
}
}
This would print:
I'm the child.
Uncomment the commented line and it would print:
I'm the parent.
I'm the child.
You should look for the concept of Polymorphism.
Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.
public class Parent {
public int add(int m, int n){
return m+n;
}
}
public class Child extends Parent{
public int add(int m,int n,int o){
return super.add(super.add(m, n),0);
}
}
public class SimpleInheritanceTest {
public static void main(String[] a){
Child child = new Child();
child.add(10, 11);
}
}
The add method in the Child class calls super.add to reuse the addition logic.
First of all, it is a bad design, if you need something like that, it is good idea to refactor, e.g. by renaming the method.
Java allows calling of overriden method using the "super" keyword, but only one level up in the hierarchy, I am not sure, maybe Scala and some other JVM languages support it for any level.
Say the hierarchy is C->B->A with A being the base class.
I think there's more to fixing this than renaming a method. That will work but is that a fix?
One way is to refactor all the functionality common to B and C into D, and let B and C inherit from D: (B,C)->D->A Now the method in B that was hiding A's implementation from C is specific to B and stays there. This allows C to invoke the method in A without any hokery.
NOTE calling parent method via super will only work on parent class,
If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();
interface Vehicle {
//Non abstract method
public default void printVehicleTypeName() { //default keyword can be used only in interface.
System.out.println("Vehicle");
}
}
class FordFigo extends FordImpl implements Vehicle, Ford {
#Override
public void printVehicleTypeName() {
System.out.println("Figo");
Vehicle.super.printVehicleTypeName();
}
}
Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.