Extend object and inherit all variables - java

Let's say I have an object of the class Car, with like 30 variables ranging from top speed to color. I want to make a MyCar object (class MyCar extends Car) that is basically the same thing except it stores some more information.
It is not possible for me to create MyCar objects right away (since out of thousands of Car objects only a few will become MyCar objects), unless I leave the additional fields blank, but that doesn't seem too professional. And neither does creating a constructor which takes 30 arguments, or setting 30 arguments through method calls.
So, is there any way to easily inherit all the variables from a superclass object?
PS: My program is not about cars, but I figured it would be an easier example.
EDIT
Thanks for the replies. They are all helpful for my program, but not for this particular problem. Builders don't seem beneficial because these cars of mine don't have default values for their variables. Every time a car is made, all the variables are filled out (which is needed to construct a sort of "fact-sheet").
Envelopes are an interesting design, but still require me to copy all the variables in the subclass constructor. I was hoping there would be a way to circumvent this. Templates would also require me to copy all the variables one by one.
In my program the subclass acts as a sort of "wrapper class" in a search engine. The subclasses are the same as the normal cars, but they have a "ranking score". My program is designed to display regular cars, and by extending those I can easily display the subclasses and order them by score at the same time.
I have to create new objects anyway, because multiple searches can be performed on the same list of cars. So editing variables in the original cars was not an option.
Maybe there is a better solution to this problem, but for now I guess I'll have to pass the superclass object into the constructor and copy all the variables there.
Thanks for the help!
PS: I'm just thinking, perhaps I could throw all the variables into a HashMap. That way I could access them by using .get(varname), and I would only have to pass one HashMap variable into the subclass. Downside is I would have to cast a lot, since the vars are a mixture of Strings, ints, doubles etc. What do you think, is it acceptable coding style?

Effective Java 2nd Edition, Item 2: Consider a builder when faced with many constructor parameters
And neither does creating a
constructor which takes 30 arguments,
or setting 30 arguments through method
calls.
If you are facing a constructor with too many parameters then you might want to have a look at: The Builder Pattern.
The idea is to set only the field you want/know into the builder, without bothering with the optional ones, or ones that you'd want to use default values, then calling build() to construct the actual object. See the Java examples in that article.
Once you have setup that pattern, you can construct Cars this way (notice the clean structure):
Car car = new Car.Builder(required_param1, required_param2)
.color(RED) // optional params
.topSpeed(300)
.zeroToHundred(2)
.build();

You can add a constructor that gets a Car object and copy the values from the Car to the new MyCar.

It is not possible for me to create MyCar objects right away (since out of thousands of Car objects only a few will become MyCar objects),
So, you'll have lots of objects of Car type, a few of which you'd like to, at runtime, "promote" to SpecialCar type?
Do SpecialCars have exactly the same interface as Cars?
You might want to read up on Coplien's Envelope-Letter Pattern, it's a way of "changing" object type at runtime. The object doesn't really change type, of course; instead, a different "Letter" goes into the existing "Envelope". The Envelope is the handle that other code references, but method calls on the Envelope are delegated to the Letter:
class CarEnvelope { // an envelope
Car c ; // the letter
CarEnvelope( Car c ) { this.c = c ; }
int someMethod() {
return c.someMethod(); // delegate
}
void promoteToSpecialType() {
if( ! c.isSpecialCar() ) {
c = new SpecialCar( c ) ;
}
}
class Car {
Car() {}
int someMethod() { do Car stuff }
boolean isSpecial() { return false; }
}
class SpecialCar extends Car {
SpecialCar( Car c ) { /*copy c's attributes...*/ }
int someMethod() { do SpecialCar stuff}
boolean isSpecial() { return true; }
}
CarEnvelope c = new CarEnvelope( new Car() ) ;
// do stuff with c
c.someMethod(); // indirectly calls Car.someMethod();
// promote
c.promoteToSpecialType();
c.someMethod(); // indirectly calls SpecialCar.someMethod

OP here.
I understand that this looks like laziness. But I already have it working by manually copying 30 variables in the constructor. Not that big of a task, I know.
The thing is, I have been taught to code with style. When I see mindless code blocks that look like copypasta my instincts tell me that there is probably a better way. So my desire to learn and strive for perfection has driven me here.
But if there really is no other way than to copy the variables (or override all the get&set methods) then I don't have to look any further.
Needless to say, all the replies in this topic have given me new insights. Thanks guys.

I have a feeling that what you are looking for is the notion of a template; e.g.
public class Car {
private final int attr1;
private final int attr2;
...
public Car() {
super();
}
/* copy constructor */
public Car(Car template) {
this.attr1 = template.attr1;
this.attr2 = template.attr2;
...
}
/* setters and getters */
}
Then ...
Car myTemplate = new Car();
myTemplate.setAttr1(3);
myTemplate.setAttr2(11);
...
Car car1 = new Car(myTemplate);
car1.setAttr1(4);
Car car2 = new Car(myTemplate);
car1.setAttr1(5);

I don't get it. What's wrong with a regular inheritance?
class Car {
private int attributeOne;
.....
private boolean attrbuteThirty;
public void methodOne(){...}
...
public void methodThirty(){...}
}
And then just subclass it:
class SubCar extends Car {
private int extraAttribute;
}
All the 30+ attributes and methods are already inherited, that's what the extends is all about.
If what you need is to create a new object based on the data of an existing one, but you're resisting to code it! ( ¬¬ ) , then you may just create a small script to create the code for you. It's very easy. You copy/paste the generated code and you're done.
If you don't want to do it, because you don't want to duplicate the data, you may override interesting methods, and delegate the code to the original, that's what the Decorator design pattern is all about:
class SubCar extends Car {
private Car wrapped;
private String extraAttribute;
public SubCar( Car original, String newAttributeOne ) {
wrapped = original;
this.extraAttribute = newAttributeOne;
}
public void someMethod() {
wrapped.someMethod();
}
public String getName() { return wrapped.getName(); }
... and so on
// new method
public String extraAttribute() { return extraAttribute; }
}
That way you won't duplicate the data, but just decorate it.

We can create an interface ICar that has all the getters and setters for all the 30 columns.
Car can implement ICar and can contain all the 30 fields with their corresponding getters and setters.
MyCar can also implement ICar and can use composition. It exposes Car's methods as delegate methods (which can automatically be generated in an IDE like eclipse)
public interface ICar {
// getter and setter methods
}
public Car implements ICar {
private String color;
// getters and setters for each of the fields
}
public MyCar implements ICar {
private Car car;
public MyCar(Car car){
this.car = car;
}
public String getColor() {
return car.getColor();
}
}
All consumers could then use the ICar interface for their manipulation. Will that work?

Related

Adding new attribute to an existing object

I would like to ask something about an issue i have.
Lets say we have an interface called Vehicle.
Then we have a class that implements this interface called Car.
Then another one called Bicycle.
Now the whole code uses these two objects (Car, Bicycle) and whenever needed interface Vehicle.
What if now i want to add a new attribute to Car class and due to this change also modify some of its methods. For example i can extend Car with a class called Car2. But now if i want to make use of Car2 in the code i will have to rewrite every single method and class that uses Car to a new class that will use Car2.
For example a method that does not belong to Car class.
int checkSpeed(Car c) {
speed = c.attributeX * 100
}
Now i want this method to be able to accept Car2 also and change the way it calculates its speed. Do i need to rewrite the class and method or is there an easier way to do it?
Keep in mind that i dont want to completely modify Car, i just want to have both Car and Car2 and use them on demand in the same classes without having to rewrite all of them.
Thanks!
You can override the methods of super class (Car) inside a sub class (Car2), which is called polymorphism, which is one of the core principles of OOP. This principle allows us to invoke different class behaviours depending upon the actual object (Car or Car2 object) passed at runtime.
For your problem, you can follow state pattern which will provide dynamic behavior depending upon the type passed and the actual implementation of checkSpeed(), as shown below:
SpeedChecker class:
public class SpeedChecker {
int checkSpeed(Vehicle v) {
//depending upon the Vehicle type object passed, checkSpeed() will be called
v.checkSpeed();
}
}
Car Class:
public Car implements Vehicle {
int checkSpeed(Car c) {
//Add specific logic for Car
}
}
Car2 Class:
public Car2 implements Vehicle {
int checkSpeed(Car c) {
//Add specific logic for Car2
}
}
as Sami Kuhmonen says :
If Car2 inherits from Car it is a Car itself
I will detail. You said :
Now i want this method to be able to accept Car2 also and change the
way it calculates its speed. Do i need to rewrite the class and method
or is there an easier way to do it?
If you don't add methods but modify their content, you should reason by programming by interface or in more general way by programming by suitable common ancestor component.
In Java, polymorphism allows not to type specifically an instance when you declare it if a base class or an interface is more suitable.
Here :
int checkSpeed(Car c) {
speed = c.attributeX * 100
}
you can send as parameter a Car or any subclasses of it, there a Car2.
So you should keep Car base class as declared type when it is suitable, especially in methods which may take the one or the other type.
It will work :
Car myCar = new Car();
checkSpeed(myCar);
Car2 myCar2 = new Car2();
checkSpeed(myCar2);
...
int checkSpeed(Car c) {
speed = c.attributeX * 100
}
It will not compile :
Car myCar = new Car();
checkSpeed(myCar);
Car2 myCar2 = new Car2();
checkSpeed(myCar2);
...
int checkSpeed(Car2 c) {
speed = c.attributeX * 100
}
You can check if the object Car c is actually of type Car2:
int checkSpeed(Car c) {
if(c instanceof Car2){
//do something if c is actually Car2, such as
use attributes that exist in Car2 but not in Car
else{
//the regular case
speed = c.attributeX * 100
}
}
Keep in mind that i dont want to completely modify Car, i just want to have both Car and Car2 and use them on demand in the same classes without having to rewrite all of them.
You already have a broken design since your sample method violates the most important principle in OOP: information hiding. Refusing to fix that because it's a lot of work will cause much more work later, just as it is doing now. This extra work will grow exponentially and harm you deadlines...
For example a method that does not belong to Car class.
int checkSpeed(Car c) {
speed = c.attributeX * 100
}
Lets forget for a moment that this doesn't even compile...
Now i want this method to be able to accept Car2 also and change the way it calculates its speed. Do i need to rewrite the class and method or is there an easier way to do it?
If this method would be part of the Vehicle interface and implemented in Car (and Bicycle) you could simply implement it in Car2 any way you want. without changing anything else in your program.
And That's what OOP is all about. But you get that advantage only if you know and follow its principles...
Сlearer approach in this case would be letting the Vehicle object itself to determine how should speed be calculated. This makes sense since all information is needed to do that is already encapsulated in the Vehicle class.
What I mean is have an interface like that:
pulbic interface Vehicle {
int getSpeed();
}
And implementations of the interface. For Car:
public class Car implements Vehicle {
// some car stuff
...
#Override
public int getSpeed() {
return carspeed;
}
...
}
And for Car2:
public class Car2 implements Vehicle {
// some car2 stuff
...
#Override
public int getSpeed() {
return car2speed;
}
...
}
Now your checker method can look like this:
public int checkSpeed(Vehicle v) {
int speed = v.getSpeed();
// do the checks
...
return someResult;
}
This way you don't really need to know the type of the vehicle itself to be able to check its speed. This is the whole point of polymorphism.
And in case you can't modify existing interface, I would suggest you to extend original Vehicle interface with SpeedVehicle that contains all required methods, and build a class hierarchy based on it.
If Car2 is always a Car and needs all the behaviors of Car, then you need to make Car2 a inherit from Car. If Car2 is not always a Car, but they have common ground, then you need to determine what that common ground is, implement it as a BaseCar class or an ICar interface if the implementations totally differ and Car along with Car2 should be inherited from BaseCar/ICar.

Java - cloning through extending

Imagine situation:
I have got two classes
public class Fruit{
}
and:
public class FruitOnSale extends Fruit{
int price;
public int getPrice() or something
}
My program has one fruit and one fruitOnSale object. I would like to create completly new (clone) fruit2 [Fruit] based on the fruitOnSale (for example somebody has bought fruitOnSale and it needs to appear in his bag but as a normal fruit cause it is no more in shop). The method getPrice and field price are deleted during it.
Then backwards - somebody creates a shop (...) and puts his fruit on sale. Now I need to convert fruit to FruitOnSale (I want it to be in the shop as 'on sale' and in my bag as 'normal', but as independent objects).
These classes will be rebuilded, modified and lots work may be done on them, so I don't want to manualy rewrite them just by copying every field because it's sensless. Is it possible through clonning? Or have you got better ideas?
Use composition:
public class Fruit {
// your regular fruit class
}
Your "fruit on sale":
public class FruitOnSale {
private Fruit fruit;
private int price;
public FruitOnSale(Fruit fruit, int price) {
this.fruit = new Fruit(fruit.getName());
this.price = price;
}
public Fruit getFruit() {
return Fruit(fruit.getName());
}
}
Now you can construct FruitOnSale instances by passing in a Fruit instance, and you can get a Fruit instance from FruitOnSale instance as well. Notice that when you initialize a FruitOnSale instance with a Fruit instance, it creates a "copy" of the Fruit instance. It's good to do this, otherwise you could modify the original Fruit instance, which would then affect the FruitOnSale instance. This is not what you want, if you are assuming that these are immutable. Similarly, getFruit() doesn't return a reference to the internal instance, but creates an entirely-new Fruit instance as well.
While solving this particular example using inheritance does not violate the Liskov Substitution Principle, in general it is a good idea to think about the impact of extending the base class. For example, there might be some things that you can do with Fruit, that don't make sense with FruitOnSale (i.e., could lead to inconsistent, illogical, or unpredictable behavior); this would be an example of LSP being violated.
Cloning and Inheritance are two very different and very unrelated concepts in which both is unlikely to help you in your current case, if I understand you correctly.
Cloning normally refers to when you want to duplicate existing objects at runtime, thus the term should be avoided when used in a programming context unless the subject matter actually has relevance to the concept of object cloning.
Inheritance is used in contexts where you want to provide a more specific version or an alternative implementation of something, thereby extending the features of the more vague/abstract version with addition/altered functionality.
To give an example, we can declare two classes as follows:
public class WoodenFurniture{
public void burn(){
// Implementation here
}
}
and
public class WoodenChair extends WoodenFurniture{
public void sit(){
// Implementation here
}
}
Note in this case, WoodenChair is a more specific version of WoodenFurniture and thus WoodenChair inherits all functionality of WoodenFurniture, including the aforementioned burn() method.
Whilst your Fruit and FruitOnSale class demonstrates such a relationship, where FruitOnSale is a more specific version of Fruit, your application of inheritance is incorrect.
In your question body, you suggest mutating a Fruit object between multiple states carrying different information should be done through inheritance, which is only true if you are continuously adding or specifying detail to your current object. In this particular case, composition should be used, as described by Vivin Paliath.
But in the case you are describing, you want to repeatedly change or toggle between different states of the same object. Especially by saying method getPrice and field price are deleted during it you demonstrate inheritance is not what you want. This should be done by adding fields to your original object to append state-specific information as opposed to the creation of multiple classes, as follows:
public class Fruit{
private boolean onSale = false;
private int price = 0;
/**
* Retrieves the price of the fruit if it is on sale.
*/
public int getPrice(){
// Check if the fruit is in the onSale state
if(!onSale){
// Rather than throwing exception, you can alternatively return an invalid price e.g. -1 to denote "not for sale"
throw new IllegalStateException("not on sale");
}
return price;
}
public void putOnSale(int price){
this.price = price;
onSale = true;
}
public void takeOffSale(){
onSale = false;
}
}
The class above represents an example implementation of something on the lines of what you want. In this case, we do not need to go through the trouble of converting between object types nor break any inheritance policy regarding how objects should interact.

Keeping track of all instances of a subclass in the superclass

I have the following, stripped-down Java code:
// Class, in it's own file
import java.util.*;
public class Superclass {
protected List<Subclass> instances = new ArrayList<>();
public class Subclass extends Superclass {
private int someField;
public Subclass(int someValue) {
this.someField = someValue;
updateSuperclass();
}
private void updateSuperclass() {
super.instances.add(this);
}
}
}
// Implementation, somewhere else, everything has been imported properly
Superclass big = new Superclass();
Subclass little1 = big.new Subclass(1);
Subclass little2 = big.new Subclass(2);
Subclass little3 = big.new Subclass(3);
I want to implement a method in Superclass to do something with all the Subclasses. When a Subclass is created, it should add itself to a list in Superclass, but whenever I try to loop through that list in Superclass, it says the size is 1. The first element in the list (instances.get(0)) just spits out a String with all the proper information, but not in object form, and not separately. It's like every time I go to add to the list, it gets appended to the first (or zeroeth) element in String form.
How can I solve this so I can maintain an ArrayList of Subclasses to later loop over and run methods from? I'm definitely a beginner at Java, which doesn't help my case.
If all you need is a count then I suggest a static value that is updated in the constructor of the parent class.
private static int instanceCount = 0;
public Constructor() {
instanceCount++;
}
If you absolutely need every instance in a list so you can do something with them then I recommend you strongly re-consider your design.
You can always create a utility class that will let you maintain the list of objects to run processes on. It's more "Object Oriented" that way. You can also create one class that has all of the operations and then a simpler bean class that has only the data values.
But, if you insist, you can still use the same technique.
private static List<SuperClass> list = new LinkedList<SuperClass>;
public Constructor() {
list.add(this)
}
Each instance gets its own copy of your superclass's variables.
What you want to do is make the variable "static" by putting the static keyword before it. You probably don't even need the superclass accomplish what you're trying to do.

Prototype Pattern in Java - the clone() method

So, I've been reading on Design Patterns and the Prototype Patterns confuses me. I believe one of the points of using it is avoiding the need for using the new operator. Then I look at this example:
http://sourcemaking.com/design_patterns/prototype/java/1
First, Their idea of Prototype implements a clone() method, which is weird. Wikipedia also says I need a pure virtual method clone to be implemented by subclasses (why?). Doesn't Java already provide such a method, doing exactly what we need it to do (which is to create a copy of an object instead of instancing it from scratch)? Second, the clone method invokes the operator new! Surely the example is wrong? (In that case I should be studying Design Patterns elsewhere, heh?). Can someone tell if this correction makes it right?:
static class Tom implements Cloneable implements Xyz {
public Xyz cloan() {
return Tom.clone(); //instead of new I use clone() from Interface Cloneable
}
public String toString() {
return "ttt";
}
}
Any clarification is appreciated.
The idea of prototype pattern is having a blueprint / template from which you can spawn your instance. It's not merely to "avoid using new in Java"
If you implement prototype pattern in Java, then yes by all means override the existing clone() method from Object class, no need to create a new one. (Also need implement Clonable interface or you'll get exception)
As an example:
// Student class implements Clonable
Student rookieStudentPrototype = new Student();
rookieStudentPrototype.setStatus("Rookie");
rookieStudentPrototype.setYear(1);
// By using prototype pattern here we don't need to re-set status and
// year, only the name. Status and year already copied by clone
Student tom = rookieStudentPrototype.clone();
tom.setName("Tom");
Student sarah = rookieStudentPrototype.clone();
sarah.setName("Sarah");
A design pattern is simply a way of representing how software is written in a reproducible way. There are in fact different syntactical approaches to achieving the same thing.
So, the Prototype pattern is simply an approach that uses a master copy to implement some overriding functionality. There are several ways to do this in Java (as well, I believe in other languages). Here is one that uses the 'new' keyword, and it's based on using an interface as a contract with implementing concrete classes. Then a single method takes a concrete implementation of the interface and performs the same operation:
// software contract
interface Shape {
public void draw();
}
// concrete implementations
class Line implements Shape {
public void draw() {
System.out.println("line");
}
}
class Square implements Shape {
public void draw() {
System.out.println("square");
}
}
...
class Painting {
public static void main (String[] args) {
Shape s1 = new Line ();
Shape s2 = new Square ();
...
paint (s1);
paint (s2);
...
}
// single method executes against the software contract as a prototype
static void paint (Shape s) {
s.draw ();
}
}
You can read more at http://www.javacamp.org/designPattern/prototype.html or check out the main Design Pattern site. The information is presented there complete with references.
The example you've linked is correct and your code
return Tom.clone();
won't compile because clone() is not a static method.
Cloning is not about avoiding the use of new operator but creating a new instance that has the same state (values of its member fields) as that of the object that's being cloned. Hence, clone() is not static but an instance method so that you can create a new instance (and using new isn't a problem) that mirrors the state of the object that clone() has been invoked upon.
It's just that your example classes (like Tom) are so simple (with no state) that all that the clone() method is doing is to instantiate a new instance. If it had a bit more complex state (say an ArrayList of objects) the clone() method would have to do a deep copy of the ArrayList as well.
To elaborate with one of your example classes, assume that Tom had some instance state. Now, the clone() would also have to make sure that the copy being returned matches the state of the current one.
static class Tom implements Xyz {
private String name;
public Tom() {
this.name = "Tom"; // some state
}
public Xyz clone() {
Tom t = new Tom();
t.setName(getName()); // copy current state
return t;
}
public String toString() {
return getName();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
You can also use BeanUtils.copyProperties method to do the same which is provided by Spring framework org.springframework.beans.BeanUtils;
Prototype actually "Doesn't" save calls to new operator. It simply facilitates that a shallow copy of non-sensitive attributes are made by calling the so called clone. For example,
1) You have UserAccount which has a primary user and linked user details
2) UserAccount also has it's PK called userAccountId.
When you put all your UserAccount objects in a collection, of course, you would like the userAccountId to be different. But you still have to call new UserAccount for each links you have. Otherwise, you will end up modifying one object 100 times expecting 100 things in return. Also, if you have this UserAccount as a composition (not aggregation) depending on the attribute's sensitivity, you may have to call new on them too.
e.g if UserAccount has Person object (and if 'Person' has it's own compositions), you have to call new to ensure that their references are appropriately set.

Confusion about extended classes in Java

I am having some confusion about extended classes. I think the best way to explain what I want to do is with some skeleton code:
abstract class Player
{
public int solve()
{ // One method of solving problem
}
}
class otherPlayer extends Player
{
public char solve(int num)
{ //Different method of solving same problem
}
}
// I suspect this is a wrong way to create Player
Player first = new otherPlayer;
// Because this gives me an error...
first.solve(5)'
// And this uses the super class's method of solving problem
first.solve();
// I don't want to do this though...
otherPlayer first = new otherPlayer;
// Because I actually define the Players in a method
// that returns a type Player():
private Player genPlayer()
{ // Take input from keyboard
Player newPlayer;
if (specific set of answers)
newPlayer = new otherPlayer();
else newPlayer = new Player();
return newPlayer;
}
My understanding of extended classes is limited. If I say "TypeA var = new TypeB", and TypeB extends TypeA, it seems that var only has access to methods in the TypeA class. What does it do, then to say it is a new TypeB? Why is that even a legal way to instantiate a variable? And how would you recommend I restructure this program so I can make it work (I'd prefer to keep the method, so I don't have to make a mess every time I create a Player)?
I really just want to know how to create an extended class as if I were a person who knew what he was doing.
You need to do something like:
abstract class Player {
abstract void solve(int num);
}
class OtherPlayer extends Player {
void solve(int num) {
//...
}
}
That is, to call a method through variables of type Player, at least its signature must be declared on that class - and must be implemented in all subclasses. There is no way to call a method that may or may not exist in a subclass using a variable of the superclass type.
Imagine you could do this:
class Player {
// ...
}
class FooPlayer extends Player {
void solveInt(int num) {
// ...
}
}
class BarPlayer extend Player {
void solveString(String s) {
// ...
}
}
Player[] players = new[] {new FooPlayer(), new BarPlayer()};
// this is the sort of code you want to work
for (Player p : players) {
p.solveInt(123);
}
what's supposed to happen when the method is called on BarPlayer? As you can see, it doesn't make much sense to allow this.
While it's not very useful to do Player player = new FooPlayer() explicitly, it does let you not have to know which exact subtype of Player the value is. It's missing the point to look at the methods that are different between the subtypes - the point of polymorphism is that the same method (i.e. with the same signature) is implemented in a different way between the subclasses:
class Player {
abstract String greet();
}
class EnglishPlayer extends Player {
String greet() {
return "Hello";
}
}
class JapanesePlayer extends Player {
String greet() {
return "Konnichi wa";
}
}
The point of TypeA a = new TypeB() is programming to contract. It means you can change TypeB into any other type that extends TypeA and be guaranteed not to have to change any other line of your code.
first, you are getting an error in the instantiation syntax. It should be new otherPlayer(). Also classes should be capitalized in java.
I assume the code is within a method, otherwise it will not compile.
Finally, to answer your question why you extend a class, if otherPlayer had its own implementation solve() (no arguments) then which method would be called would depend on the instantiation you used, not on the variable type. In other words, first.solve() would call the method in otherPlayer, not in player.
extension is about superclasses and subclasses.
if typeA is a subclass of typeB, then you could say
typeA extends typeB, and typeA would inherit all of the methods of typeB
it only works one way, kind of like a child can inherit traits from their parents, but the parents don't inherit anything from the child
if you want a method in the subclass to behave differently than in the parent class, simply write a new method with the same name/parameters. subclass methods automatically override superclass methods. then, if you want to use the superclass version of a method, you can use the super keyword
Inheritance is something that happens when you extend a class, you need to figure out the common methods you want in your class and subclass and define any alternates in your subclass.
Check this out for more info: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
you declared 'first' as a Player reference that is referencing an otherPlayer object. This is legal, but if you want otherPlayer behavior, you will have to typecat 'first':
((otherPlayer)first).solve(5)
First of all, you can't instantiate abstract classes, so you can't code newPlayer = new Player();.
Then, it's perfectly legal to write something like ClassA a = new ClassB(); as long as ClassB is a subclass of ClassA and ClassB is not an abstract class.
In the case you have a method in ClassB that overrides a method of ClassA, which one is called depends on the dynamic type of the object that is actually the type you used for instantiate that object, this is called Polymorphism. There is lot of material about this (Object Oriented Programming and Java) on the web, but I think a great place to start at, is the book Thinking in Java by Bruce Eckel, he offers the third edition for free at his site (http://www.mindview.net/Books/TIJ/).

Categories

Resources