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....
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 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=_=
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 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 8 years ago.
Improve this question
Super class being an abstract class creates an overhead for all its sub classes to compulsorily define its abstract methods. I understand that it's very basic but I need to know why do programmers usually make super class as an abstract class, though we can do similar things using a super class as a non abstract class.
An abstract superclass is one way to provide re-usable code.
You can extend the abstract class and inherit the code. This is sometimes more convenient than using static methods or object composition to share code.
The abstract class can "fix" parts of the code (by making it final). This is called the "template method" pattern (and this is not possible with an interface, which cannot provide final methods).
Of course, you can achieve both with a non-abstract superclass as well.
An abstract class has the additional benefit that it does not have to provide a complete implementation (that would make sense to instantiate on its own), some parts can be left specified, but unimplemented (the abstract methods).
imagine you have a common behaviour where only small details are specific to the implementation - then you can put all the common behaviour in a abstract base class and having some abstract methods that the implementing classes need to fill.
For example a abstract repository base class might implement all the details to contact your server, etc. and concrete repositories just need to fill in the details to read the right object from the right table, etc.
Abstarct classes are meant for 'abstracting'. means if some classes are having common behaviour, instead of writing evry time the same thing in each class, write that in one class and ask the other classes to use it [by making the classes as subclasses to the abstract class]. This is nothing but inheritance. To summarise: Use abstract classes when you want default behaviour for some classes Use interfaces when you want different behaviour different classes.
For More explanations Refer below links:
http://www.javacoffeebreak.com/faq/faq0084.html
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
several usage of abstract class:
act as the protocol when tranfering data between objects, the two customers need not to know other class's structure. ----- just like the interface
define the abstract operation, which hides the detailed implementation of concrete class, for example, I have a class called AbstractPayment, which define the opration of charging money from customer, then the concrete classese of it could be: PaypalPayment, AlipayPayment, BankPayment and others. BUT, for the class customer, it only needs to know the AbstractPayment.
after some time, if you need to add another ConcretePayment, or modify one other payment, the customer class won't change.
Abstraction is largely used in design patterns, I suggest you to read following:
Abstract Factory Pattern
STO
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am looking for a ans what I have found in facebook and became confused
"is it possible to declare a constructor inside a method"
Short answer: no.
Long answer: This comes from the Java Language Specification, §8.8:
A constructor is used in the creation of an object that is an instance of a class.
In all other respects, the constructor declaration looks just like a method declaration that has no result (§8.4.5).
Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.
It's declared like this:
ConstructorDeclaration:
ConstructorModifiers(opt) ConstructorDeclarator
Throws(opt) ConstructorBody
ConstructorDeclarator:
TypeParameters(opt) SimpleTypeName ( FormalParameterList(opt) )
A ConstructorDeclarator can only live inside of the class body declaration:
ClassBody:
{ ClassBodyDeclarations(opt) }
ClassBodyDeclarations:
ClassBodyDeclaration
ClassBodyDeclarations ClassBodyDeclaration
ClassBodyDeclaration:
ClassMemberDeclaration
InstanceInitializer
StaticInitializer
ConstructorDeclaration <--
ClassMemberDeclaration:
FieldDeclaration
MethodDeclaration
ClassDeclaration
InterfaceDeclaration
;
A MethodDeclaration has no symbol to a ConstructorDeclaration, which is why you cannot declare a constructor inside of a method.
You cannot declare a constructor inside a method.
Constructors and methods are both components of objects. Your object has a constructor that gets called when you instantiate it. Once instantiated, your object then has properties to define it, and methods to do things with.
If you try to place a constructor into a declaration, you will get a compilation error.
This comes from several years of practice and study for the Sun certification tests.
No it is not possible.java does not support inner methods concept.Constructor is also like a method.Constructors can be declared inside a class only.
The constructor is sort of a method much like the main method. The constructor is used to initialize an object of the class and it has no return value.
Not at all possible.
A constructor must invoked while creating object for a class.
With out instance how you will call that method,which is building the constructor?.
Making any sense ?