I am new to java and I am trying to create an XML document and clone a specific node (minus the textnode) of this document over and over again. Someone answered me and said that I should subclass the node and override the cloning. So my question is what is sub-classing?
Subclassing means to define a new class that has the properties of an old class (the "superclass") with some changes.
In this case, your original responder is saying something like this:
Say you have a base class Base which has a method getTwo like so:
class Base {
public int getTwo(){ return 2;}
}
You decide you want a new class that still have a method getTwo but that returns the string "two" instead of the number 2. You could define it as
class Subclass extends Base {
public String getTwo() { return "two"; }
}
We say Subclass is a subclass of -- or more commonly, "is a kind of" -- Base.
Beyond that, you'd be best off to read a book on object-oriented programming with Java. I'm fond of Thinking in Java, which has the added advantage that it's available freely on line.
#Charlie Martin has explained what subclassing means.
However, it is not clear that you've been given good advice. If you are creating the XML document by assembling a DOM in memory, a better approach would be to create a helper class with static methods that perform the sequence of DOM node operations that you need to do.
In short Answer : A Superclass can be Subclassed - That means for a specific class we can find/create a subclass that extend it.
Subclass represents is a relationship in Object-Oriented Programming (Inheritance).
For example
The Circle is a Shap.
So we can say:
The Circle class is a subclass of Shape class.
Related
I have confusion regarding Method Overriding in java.
From it's definition it says :
In any object-oriented programming language, Overriding is a feature
that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its
super-classes or parent classes.
Now, below is one example regarding it :
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}
class Child extends Parent {
#Override
void show()
{
System.out.println("Child's show()");
}
}
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.show();
Parent obj2 = new Child();
obj2.show();
}
}
I have doubt at this line :
Parent obj2 = new Child();
I can do the same thing using :
Child obj2 = new Child();
then why I need to declare it with the name Parent class?
What it's purpose?
Like you said, you don't need to declare subclass objects as their parent class, but there are other cases where this may be important, such as when you are trying to make things abstract.
What is Abstraction?
Abstraction is removing everything but the most essential. A really good example you probably already use a ton is Lists.
Whether you are using an ArrayList, a LinkedList, or any other type of Java list, you know that there are certain properties that you can always count on being there, like getting the size of the list, getting a certain element at a certain point, etc.
This DRAMATICALLY simplifies the use of these, and you can interchange them depending on your application. This is all because they are a subclass of List, in which these methods come from.
The ways that an ArrayList, and a LinkedList get and set data are different, but from the perspective of you, the user of these sub classes, the implementation is the same, you just use the classes that were overridden. It's super convenient, because you don't need to know a thing about coding, try whatever you're trying to do with a linkedlist, then with an arraylist, and see whats faster.
What's your part in this?
In the example you gave, it is very simple, and doesn't matter, but say you were making a class that sorted lists in a particular, fun, amazing way.
If you declared everything as just a List, users of your class could pass in both ArrayLists, and LinkedLists, depending on what they were doing, and both would work. So, to be a good programmer, try to keep everything as abstract as possible. It's a good rule to learn early on.
Inheritance allows us to reuse of code, it improves reusability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class need not be rewritten in the child class.
I've got a task to do polymorphism but I am not entirely sure I understand the concept as per testimony of my teacher.
According to web definitions and examples, this by all means is polymorphism, but they say it is not. Can I please get confirmation?
OversizedParcel.java
public class OversizedParcel implements ParcelType {
public void resolve(PrivateUser user) {
//do theese
//and those
}
public void resolve(LegalUser user) {
//do different thing
//and a completely different thing
}
}
IllegalParcel.java
public class IllegalParcel implements ParcelType {
public void resolve(PrivateUser user) {
//do this
//do that
}
public void resolve(LegalUser user) {
//do a thing
//do a different thing
}
}
(hypothetical class)
public class Main{
private User user; //loaded user
private List<ParcelType> parcels; //assume this contains the loaded parcels already
public static void main(String[] args){
for(ParcelType type : parcels) type.resolve(user);
}
}
Polymorphism can be defined as -
it is the ability of an object to take on many forms
. The most common example of polymorphism could be-
when a parent class reference is used to refer to a child class
object.
So as per your question, in most simplistic way polymorphism can be defined as
ParcelType oversizedparcel = new oversizedParcel();
ParcelType illegalparcel = new illegalParcel();
Here ParcelType can be a oversizedParcel or illegalparcel
So if your understanding is as per my answer, then indeed it is an example of polymorphism.
I'd like to offer a dissenting opinion from what appears to be majority here. Keep in mind that "Polymorphism" is a fairly flexible term, and that what is written here does not necessitate 100% universal truth. This is simply something to aid the balance of thought.
No, what you have written is not polymorphism. This is due to the fact that they instantiate different unrelated objects that simply implement the same interface.
Traditionally, Polymorphism occurs when you have a child object that overrides a parent object's implementation of a method. Hence, there is "multiple forms" of a method that exist at the same time at different levels of the object's vertical hierarchy.
However, interfaces are merely an agreed-upon contract of inputs and outputs that standardize interactions. They don't by themselves hold an instance of the code (we shall exclude default interface methods for the sake of this conversation). Because of this, there is no "Re-definition" of the interface within an object. the same object tree does not instantiate multiple versions of the interface (unless it is through the traditional view of polymorphism).
Even if a method required two arguments of interface ParcelType, it does not necessarily mean polymorphism, it simply means that the method is asking for two 'boxes' of a particular shape and size. These boxes are empty until they are passed into the method as two distinctly different objects that are referenced separately (And not the same method object being overridden by a child object, for example)
Different objects can take advantage of the interface contract, and in a way you can say that it is "Horizontal Polymorphism", but I think this is taking away from the intention of what polymorphism means in the context of Java.
According to the W3School definition, it is indeed polymorphism. Anyway, if your teachers said it is not, they may have been expecting you to do something else.
Polymorphism is, to go further than just an example, an entire concept meaning that you can do entirely different things by using "the same things", or more exactly "things named the same".
Have a look on the Wikipedia definition, which is more complete than any language-specific one, to have a wider view on it.
Polymorphism is having the same thing in different forms. So, Yes this is polymorphism.
I assume that resolve is defined in ParcelType interface. Then the type.resolve calls in for(ParcelType type : parcels) type.resolve(user) are dispatched polymorphically on ParcelType
I would like to know if it safe and a good practice to keep common code in a separate class and make method static.
I have a class Car, that is constructed based on inputs from other classes. I need to apply some post construct processing after the Car object is created. Example below.
Class Travel uses Car and calls postConstructProcessing method.
CarProcessor is simillary used in other classes whenever car object is creates.
My question is should I make method process Static in CarProcessor.
Class car{
Type type;
Int model
Car(Type t, int m){
...
...
}
;
....
...}
Below class of code uses Car and calls postConstructProcessing method
public class Travel {
public void go(){
....
....
Car c = new Car(t,m);
new CarProcessor().process(c);
}
}
class CarProcessor{
public Car process(Car c){
If(c.type.value.equals("ABC"){
c.type.version=1.1;
}
if(c.model=5.7){
c.price=50k
}
}
}
My question is , is it safe and a good practice to make method process in CarProcessor static.
In general it's not great.
The most obvious problem is, if you are testing the go method, how do you replace/mock out CarProcessor::process?
The real problem is organizational though. When you are coding next time and looking for the functionality you'd expect to see in "Car" or "go", you type "car." or "go." into your IDE and hit ctrl-space, you'd expect to see all the interesting methods shown to you. How do you know to create a CarProcessor to proceed?
Some things are difficult to implement in OO though--in particular utilities. Look at the entire Math package in the java library. It's full of static methods that you just call. An oo fanatic would say these all belong in the Number class (maybe something like "Number.math.sqrt()?", but java didn't take that route--in fact they don't even have a good common number class (We have one, it's not good)--
But even when we have real classes like String, we lean towards "StringUtil" and such. This has led to a HUGE number of conflicting "Util" implementations of String. In this case part of the problem is that String is immutable and we can't really back-fill it with methods (probably a good thing). but in general, OO just isn't great for general-purpose utility methods.
Functions (which is what you are proposing) are not awesome, but are heavily used. If you have the ability to modify your business classes then that's almost always a better fit for this type of code.
Just to clarify: A Function is different from a Method--methods work on members (class variables), functions are stand-alone (Might as well be static).
Functions are a very old approach at organization. OO is a somewhat newer approach invented for when the sheer number of functions become too difficult to manage (conceptually).
As we know that we can declare only the method signature and also can not create the instance of a Interface. then why we need interface. Unnecessary its loading into JVM. This is also one performance degradation. We are creating the interface and several classes implementing that interface and defining all the methods of the interface. Actually what we achieved from this interface. Could you please give me some example.
Interface is you are forcing your client to implement some specified thing, implementation will be remain to the client.Also java doesn't support multiple inheritance by extending multiple classes you can have multiple interface implemented.
For example : List declares add(..) method all the implementation of List provides it implementations.
Simpler would be.
You define an Interface Animal and a method speak() it means all Animal must will have to speak with different different implementation. Man will speak,Dog will bark,Lion will roar.
Why should we go for create class Animal extra. We can declare the speak() in every class. What is befit we will get from Animal class and implementing speak() in all the sub classes. Still I did not get this concept
Main advantage is inheritance and polymorphism [core concepts of OOP]
You are specifying Animal's behavior here also.
You can have
Animal obj = new Man();
Animal obj = getAnimalForThisCriteria(something here);//this will return some animal at runtime so you can catch instance using Animal.
You might have Three different Class Ma,Dog,Lion with same method but there is no way to tell they all are animal unless they extends or implements common class or interface, here comes the concept of structure
Having interfaces separate from classes allows for clear separation between, well, the interface of an object and its implementation. Without them you would have no standard way to indicate that some class should not contain implementation details at all.
Second, since Java does not support multiple inheritance, interfaces are a partial workaround, by allowing inheritance on the outward features of the class.
Interfaces are for when you care only about an object's capabilities, not how it achieves them.
Suppose you are writing the high level control code for a robot. You don't care about how the robot actually works, you only want to be able to tell it to go forward, backward, turn left or right, etc. Without interfaces, you would implement a abstract class called AbstractRobot that has all methods as abstract methods. At this point you have basically created an interface,but in the form of an abstract class, but one that is 'heavier' than required.
Lastly, a class can conform to multiple interfaces, but can only inherit from one class. This allows some design patterns which rely on multiple inheritance.
I'll try to explain this in simple words.
Consider your favorite Computer Game, say Counter Strike.
In this game, the players (terrorists or counter-terrorists) use weapons.
If we teach the player how to use weapon (analogous to Interface), it can use any weapon like AK47, Maverick, Shotgun, Sniper (analogous to classes which inherit Weapon interface).
The advantage of this is consider Bazooka (which implements Weapon) is developed in future versions. Then the current player will be able to use it without any modifications - as it knows how to use Weapon interface :-)
This is just a simple example. There are many other reasons for using interfaces.
An analogy for an interface is to think of a class using an interface as being like an electric wall outlet, and think of the implementation as the plug. The outlet doesn't care what's behind the plug, as long as it fits in the outlet. In psuedocode terms it could be written like this:
public interface ElectricOutlet {
public void powerUp();
}
And a class that implements ElectricOutlet might look like this:
public class Appliance implements ElectricOutlet {
//member variables
public void powerUp() {
//Draw power from the wall
}
...
}
So how do you use that interface? Like this:
//lots of other code
ElectricOutlet out = new Appliance(); //plug the appliance into the outlet
out.powerUp; //power it up!
Of course, it doesn't have to be an appliance that you plug into an outlet. It could be a TV, or a laptop, or a lawn mower, but they all behave the same way from the outlet's point of view. So how does this apply to programming? In exactly the same way:
List<String> list = new ArrayList<String>(); // create a new List of Strings
I just created a new (empty) List of Strings. If it turns out that ArrayList doesn't provide the right performance, and LinkedList works better, I can go back and change that line to this:
List<String> = new LinkedList<String>(); //should work better now
I can do this because both ArrayList and LinkedList implement the List interface, and thus they provide the same behavior (API), even though the internal implementations may be different. From the List's point of view, however, it doesn't matter what the internal workings are, just as long as the interface is there. This allows a lot of independence between classes, and allows more reuse.
Simple. I think Interfaces and Abstract classes are for the same purpose. The difference is If you extend an Abstract Class, you could not extend no other class in Java. Reason: Java does not support Multiple Inheritance. At the same time, You can implement any number of Interface for a class.
The most important use of interfaces as i see it is passing code(anonymous inner class or lambda) to a method as parameter.
Example:
Suppose we want to make a method which can return the execution time required to run a piece of code. We want to pass our code as a parameter to this method.
interface Code{
public void run();
}
long getExectutionTime(Code code){
long startTime = System.nanoTime();
code.run();
return System.nanoTime() - startTime;
}
getExecutionTime(new Code(){
public void run(){
//the code to be executed
}
});
In java 8,
getExecutionTime(()->{
//the code to be executed
});
Interface is nothing but its a guide line for the new implementation
it provides some instructions for new implementation and categorize the functionality of the object .In details like if we create an interface then we create an instruction for the implementation .
I have a bunch of classes extending an abstract Base class.
Each subclass takes an array as in the constructor, (different length depending on class).
These classes could be written by other people.
What is the best way to figure out the length of the array the class needs?
I could:
(A) Require that each derived class have a static method, returning the length.
However, the base class cannot enforce this, since abstract static methods does not work in java.
(B) Each derived class have a constructor with no arguments, and I construct
such classes just to be able to call the countParameters() method, that
I can enforce from the Base class. This feels "cludgy", since I am not interested in creating such object, but only need some info about it.
The reason is that I am creating a GUI, that gives the user the ability to create
instances of Derived classes, but each Derived class takes different number of parameters.
That is, I need to know how to draw the GUI before I can create the classes.
EDIT:
I could just require that each Derived class have a private
constructor, with no arguments, and using reflection I can call the countParameters() method.
EDIT2: Actually, what I am interested in, is what the names of the parameters are.
That is, if the class Derived have the constructor
public Derived(double name1,double name2,...)
I need a way to generate the String[] array
{name1,name2,...}
I guess this would be impossible to do without creating an instance of the class,
but for the user to be able to create such class, he/she needs the parameter names!
Moment 22.
It sounds like you need the Factory Pattern.
In general, it's a bad idea for a base class to know the set of it's descendant's. So you define another class whose job it is to know that.
If you have something like a Shape, with ThisShape and ThatShape as derived classes, then a ShapeCreator will handle the job of creating the specific set of shapes your program supports, giving each one the arguments it needs.
It's not quite clear what you're trying to achieve, but I wonder: Do the subclasses really have to take a single parameter with an array, as opposed to a list of parameters?
Constructor<?> ctor = Test.class.getConstructors()[0];
int parameterCount = ctor.getParameterTypes().length;
ctor.newInstance(new Object[parameterCount]);
how about this code:
public absract Base {
public abstract int size();
public Base(Object[] objs) {
if (objs.length != size()) {
throw new IllegalArgumentException();
}
//rest of your code.
}
each child class needs to implement size method.
hope its help.
I'd go with method A. You can't get the compiler to enforce the existence of such a method, but you can certainly enforce it in your program - no method, no work!
Seriously, this whole scheme is a bit brittle and I can't think of a way to make it significantly better. An incorrect implementation of those subclasses will bomb out, that's life.
A possible remedy would be for you to provide a set of interfaces for those subclasses, such as
SubClassTaking2Args
SubClassTaking3Args
...
and requiring your sub's to implement one of those as a marker interface. But that's just more bureaucracy with little more effect.