Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
This is pretty trivial question, but couldn't find precise answer on SO, can anybody explain what happens in the memory when I declare a variable like:
Animal obj= new Horse();
If you see above declaration type(Animal) object is different and initialisation(Horse). What happens behind the scene.
Animal obj= new Horse();
you're constructing an object obj that can do the job of either a Horse or a Animal.
Horse is inherited from Animal. This way you can access all the properties and methods of Animal.
And found this here
This is the basis for polymorphism: Imagine you have several child classes that inherit from you parent class. You want to use all these child classes through the interface / methods defined on your parent class, without worrying about the implementation details in each child class (each might do something different, but with the same overall semantics).
This is possible because the child class has a IS-A relationship with its parent class since child inherits from parent.
I'd suggest you to learn Inheritance & Polymorphism:
An Explanation of Inheritance
Polymorphism and Casting
When ever you use new keyword you create an object. Objects are created in heap. new Horse() will create an object of Horse in the heap and will do initialization as per the class Horse.java.
Now with the case presented assuming Horse inherits from Animal. Referencing the object of Horse by a variable of type Animal(Animal a = new Horse() ) does not affect the object creation ( it is created same even if you do Horse h = new Horse() ). It only restricts the invoking of the additional method present in the class Horse using variable of super class type. You need to cast it if you wish to invoke the methods of class Horse. But point to take care is that we can invoke whats there in the object created by the underlying blueprint class. Thats why if you override a method then it doesnt matter if you have a variable of super type or if you cast a variable of Horse to Animal or you simply use variabl of type Horse to reference an obkect of Horse, invoking a method which is overrided will always result in the overriden behaviour.
These are the things we as a programmers must understand, rest should be left to the JVM implementation. How it woks internally may change on different platforms but the contract and end result on top level is always the same.
When you declare like that then object will be created for Horse class and it will create in heap memory. Hope you find the enough answer. :) cheers !
this is polymorphic in java, understand? accurately,this is also called Dynamic Binding.I think , as a newbie,we just konw how to use is ok,I am new to OS , please fogive my chinese english=_=
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In Java, I created a class CommonExcelFunctions to store procedures I use across a couple projects. there are no abstract procedures in the class. To use these, I'm trying to decide if I should make my other projects extend this class, or if I should instantiate it and access them all through the instantiated object. which way makes the most sense?
Never ever use inheritance just for the sake of code reuse. The subclass relationship should be a meaningful is-a relationship, especially in a language like Java where you have only single-inheritance.
For such utility functions you describe static would probably best. Otherwise, use composition, i.e. create a member.
Similar to what #AlexisKing mentioned, I often will create a utility class (such as ExcelFunctionsUtil and create a bunch of static methods in there. This is nice when the code is to be reused in multiple places, but inheritance doesn't make sense. I think inheritance only makes sense if the sub-class could actually be considered an extension or child type of the parent class. For instance, if you created an UncommonExcelFunctions class, that would seem to be an appropriate child of CommonExcelFunctions, but an Accounting class would not make sense.
Normally when in doubt, we ask ourselves the basics. Are we having a is-a relationship or has-a relationship.
If your new classes is indeed having an is-a relationship with your CommonExcelFunction class, then you probably can extends it.
So that answers your first question - best time to extend a class.
Else if it acts like a utility class, and some examples like those provided in Java (Example: Math.max, Math.min). You can implement your methods in the class as static (No instantiation required for usage of method).
Think about this:
Scanner scn = new Scanner(System.in); //Scanner class using instance methods
Math.max() //Math class using static methods
Why would Java want to implement the methods in Scanner as non-static while in Math class as static? You probably know the answer if you spend some time to think about it.
It is not necessary if you have some methods that we want to use directly for example (get the exponent of a number, get the max of 2 numbers, rounding off a value..etc).
However it makes more sense to create instance methods (E.g. Scanner class) when we may need more than one type of scanner (Example: scanning console input, scan from file).
You should always prefer composition to inheritance.
Your new class is not a 'CommonExcelFunctions' it just uses functions from CommonExcelFunctions.
You probably will not call functions from CommonExcelFunctions on instances of your new class. There's no need to pollute interface of your new class with methods from CommonExcelFunctions. It would break encapsulation.
When you use composition you can easily tests classes that use CommonExcelFunctions passing a mock.
When you use inheritance it's very difficult to test your class (partial mocks suck).
For example go language does not support inheritance at all.
See Effective java, item 16 "Favor composition over inheritance".
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have two classes(not interface).
Suppose the classes be class A and class B.
I want to know which is more efficient and correct implementation.
I want to access the method of A from B.
Two ways:
1) class B extends A (inherits)
2) In class B:
create an object/instance of Class A, and then access the method of class A.
Which one is more efficient and correct ??
It depends. You should only use extends (for good OOP) if it is logically correct. The way I learned is with the "is a" test. If saying B "is a" A then extends would suit.
For example:
Take 3 classes Dog, Canine and Fish
Dog "is a" Canine: this is logical and passes the "is a" test so we can use extends here
Dog "is a" Fish: this is not logical and should not inherit
If your class B is a logical subclass of A then go with extends.
You should read some documents about OOP (Object Oriented Programming). As you can read in the comments I would agree that it depends on your UseCase. A common rule for designing Objects is the 'Has a' and 'Is a' relations. This means if you can say MyObject 'Has a color' then You will add a color member to your Object as a property, if you can say MyObject 'Is a' bird then you will inherit - maybe - from Object MyAnimal that you have written before. There is a third way what you can do. If your method is a pure helper method - thus it does not own a sate while it is running, which means the method is defined within an object but does not use volatile members of that object for calculation - you could write a public static method and access it by MyObject.myStaticMethod(String myArgument). You have to be carefully with this kind of methods because if you don't know how to use them wright you can run into multiple problems e.g. when writing test or if you have a clustered environment.
But for now this should be fine. So make your objects granular over their properties and functionality. Methods that are not related to your object's type should be placed in Other objects that bundle this functionality - e.g. printString functionality in a printer Object- or if the methods are stateless then put them in a static statless helper object that bundles the functionality you need.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Can someone please explain to me how to implement these these types of code and explan what the difference between the three are? I am coding in java.
I'm goign to take a shot at it because I recently tried to understand those and this is a good way to see if I did :) because If you can't explain something you haven't really understood it :)
Casting is fairly simple. It means to pretty much convert a value or object of a certain type to a different type. This way you can for example turn a float into an integer
float y = 7.0
int x = (int) y
x will now be 7.
Of course you can't simply cast any type to any other type. There are limitations which you should search for on google - i could never cover all of them.
Polymorphism sounds similar but is actually something else. As I understand it it means that certain objects can be of multiple types. For example of you have a class that extends another class any instance of the parent class can also be of the type of the derived class.
class Base {...}
class Derived extends Base {...}
Base obj1 = new Base();
Derived obj2 = new Derived();
obj1 = obj2;
Over the course of this snippet obj1 will have been an instance of Base first but then it will be an instance of Derived which is a class derived from base. This is possible because instances of derived classes contain an "inner object" (i don't know the official name) of the base class. When you cast the Base instance to an instance of Derived you will actually get this "inner object"
Hope this helps
refer to the documentation from Oracle : http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
http://docs.oracle.com/javase/tutorial/java/IandI/index.html
True polymorphism (i.e., multiple inheritance) is not available in Java. However, you can get a good approximation using "Interfaces", though your classes need to implement all of the functions provided by the interface (link to Java Interfaces).
You can also emulate multiple inheritance using delegated setters/getters on classes. This can be complicated, but it can also give you the effect of multiple inheritance.
This topic is discussed at length in this Stack Overflow post.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm wondering how does reflection on inherited classes work? It appears that the methods are not reflectively available in my superclasses constructor.
If I have a subclass "horse" of "animal", is it possible to access the methods of "horse" using reflection when I am in the "animal" superclasse's constructor? It appears not.
SuperClass constructor is always run before the child class's. So the instance of child class is never in ready state to be used as such.
Is it not possible, because constructor body of animal is invoked before body of constructor horse. Horse 'part' of object doesn't exist yet.
A superclass's ctor (or anything else, really) shouldn't be accessing sub-class-specific methods; the superclass should not know anything about classes that derive from it.
For that matter, superclasses shouldn't call methods defined by subclasses in its ctor because the object hasn't been initialized yet. Here's some discussion regarding that, with examples.
If you have an instance of a Horse, it doesn't matter where you are (including int he Animal constructor) you can access all the methods/fields of that instance.
However, if you are in a plain Animal or some other subclass, you can't access methods/fields of Horse because its not a Horse.
Yes and no. Via the reflection API you can access the methods of a subclass (or any class) if you're in a constructor. In terms of good practice, then no since an animal is not a horse.
The important thing to realize is the way that java loads classes : first the superclass is loaded, and then the subclasses.
if you need to access methods that are specific to the subclass, you will have to find another methodology.
One strategy , for example, would to embed some of the contract which your subclass is fulfilling in the superclass using interfaces or inheritance....
I am learning Java for a test (tomorrow) and am wondering about a question that will probably never come up but has got me curious.
Is it possible to create a new collection class such as a list or something that can hold only a specific type and not its sub-types? Would I use generics to achieve this goal?
Not really, or at least not practically.
Subtypes should operate like sets in mathematical set theory. If B is a subset of A, any item in B is also an item in A.
In the same way, if B is a subtype of A, any item in B is also an item of A. Thus, any collection of A must be able to maintain items of B.
That being said, there may be convulted ways that B can override certain operations to explicitly break the ability to use it in a collection or to instantiate it.
I don't think generics will solve that problem.
If you create a custom collection class, you can check the class of the object on insert using reflection, and reject it if it's not of a particular exact type. Alternatively, if you have control over the class definition for the class contained in the collection, making it final will prevent subclasses from being created. (obviously this is a problem if you need subclasses for some other use)
The question is: why would you want that. If you have a list containing animals, why would you want to fill that list only with the "base animal", but prevent dogs or cats being added to the list. One of the basic concepts of OO is that you use an instance of a subclass everywhere where you need in instance of the base class (Wikipedia: Liskov substitution principle). If that does not apply in your situation, something might be wrong with your class hierarchy.
You could use "final" in the class definition of the contained class to disallow subtyping it. I don't immediately see how you can test for this or restrict your generics to require final classes. You can use reflection to test whether the class has the final modifier set, for instance when constructing the collection, and throw if it doesn't.
If the class itself is not final, you can check every single object added to the collection to ensure that its runtime class is exactly the class the collection wants and not a subclass of it.
see http://java.sun.com/docs/books/tutorial/reflect/ for info on reflection on Java.