Inheritance. casting and polymorphism in java [closed] - java

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.

Related

Java object instantiation [closed]

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=_=

What can I do if Liskov Substitution Principle is violated? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Liskov Substitution Principle (LSP) states that if an object o1 is a type of S and it can be substituted for object o2 that is a type of T without violating the original behavior(s) of all its users, then S is a subtype of T.
The common example used to show LSP violation is Rectangle and its derivative type, Square. The argument is that although intuitively the Square seems to be subtype of Rectangle, but there is some behavior of Square which is different from Rectangle. The conclusion is that the Square cannot be a subtype of Rectangle by LSP.
All explanations I discovered end there and I find it not helpful. I want to know what should I do if I have that problem? Create S which is not a subtype of T, and then what? What solutions do I have to solve it?
Can someone please enlighten me with an answer for the overhanging question?
edit: Rather than elaborating the example here, I refer you to this article.
You can use 'HAS A' or 'USES' relationship if you can not establish 'IS A' relationship.
This means that instead of having class B inherit from class A, you can have class B contain an instance of class A. This is also good coding practice to avoid tight coupling between class A and class B.
This question is reviewed in the book Effective C++ 3rd Edition by Scott Meyers, Addison Wesley May 2005. In chapter 6, Item 32.
There Meyers makes sample class for Rectangle and class for Square which inherits the first one and talks extensively about the arising problems using assertions.
The conclusion of the Item is:
"Public inheritance means “is-a.” Everything that applies to base
classes must also apply to derived classes, because every derived
class object is a base class object."
Currently the book can be found or bought on the internet.
The LSP is a more precise definition of the "is-a" relation, if you class violates the LSP is not a suitable candidate to be derived from the base class. It is a signal that something is wrong in your design.
Two point worth to be noticed: violating LSP is going to break the base class and not the derived class, this is very dangerous in legacy code with very little tests coverage, something that has a clear "is-a" relationship in the mathematical world (like square and rectangle) they may don't share that relationship in the domain of your application.
You can extract the common properties into an interface or an abstract type and use this as base. Differences can still be implemented in the derived type.
This way you keep your IS-relation.
The lesson to be learned from LSP and the rectange/square example is that IS_A has nothing to do with maths or biology or anything that seems obviously IS_A by intuition.
IS_A is solely a relationship of behavior. Square is not a rectangle in OOP, because it doesn't have the same behavior. But rectangle has the same behavior as square plus some extra which does not violate any behavior of square. So in OOP rectangle IS_A square and it makes perfect sense to implement it like that even if it defies maths and intuition.

to use procedures from a class, when is the best time to extend a class vs. create an instance of that class? [closed]

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".

Inheriting a class vs Accessing the methods of class by creating an Object of the class in Java [closed]

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.

Role of a Class in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am going through some past exam papers and some questions are pretty basic. One of the Question is;
which of the following best describes the role of a class in the Java language?
a) A class defines where a Java program starts executing.
b) A class is a graphical user interface component.
c) A class is a specification of an object, through grouping variables and methods that define that object.
d) A class is an instance of an object containing variables and methods.
e) A class is a group of IT students in the Computing Building at the university.
I personally believe that it's 'C' but then again 'D' also seems like the role of a class(my apologies if i am wrong). I am new to Java so i'm sorry if this seems like an unprofessional question. Thanks for your help.
The answer here is C.
Think of class as a blueprint for an object.
That is, if you are building a house, you're going to have a blueprint for it. The blueprint is the class, and the house is the object.
The class will also have "appropriate" and relevant fields and methods.
For example, if you have a class named Apple, you don't want to have a method something like getHorsePower.
A class is a specification of an object, through grouping variables
and methods that define that object.
And, basically, it's a blue print of it's objects.
a) A class defines where a Java program starts executing.
INCORRECT: It depends on where main() is located.
b) A class is a graphical user interface component.
INCORRECT: To create GUI multiple classes are required.
c) A class is a specification of an object, through grouping variables and methods that define that object.
CORRECT:
d) A class is an instance of an object containing variables and methods.
INCORRECT: Object is an instance of class not vice versa.
e) A class is a group of IT students in the Computing Building at the university.
INCORRECT: Unrelated to Java

Categories

Resources