Java error creating subclass constructor - java

I trying to learn some Java and I've got stuck creating a subclass. I keep getting a There is no default constructor available in... error.
This is the code:
class Car
{
String name;
int speed;
int gear;
int drivetrain;
String direction;
String color;
String fuel;
public Car(String carName, int carSpeed, String carDirection, String carColor, int carDriveTrain, int carGear)
{
name = carName;
speed = carSpeed;
gear = carGear;
drivetrain = carDriveTrain;
direction = carDirection;
color = carColor;
fuel = "Gas";
}
void shiftGears(int newGear){gear = newGear; }
void accelerateSpeed(int acceleration){speed = speed + acceleration; }
void applyBrake(int brakingFactor){ speed = speed - brakingFactor;}
void turnWheel(String newDirection){ direction = newDirection; }
}//end of Car class
class Suv extends Car
{
void applyBrake(int brakingFactor)
{
super.applyBrake(brakingFactor);
speed = speed - brakingFactor;
}
}
The issue comes when I try to create the "Suv" subclass. What am I doing wrong? Thanks!

You probably want to create the following constructor in Suv that initialzies that parameters that the Car constructor has:
public Suv(String carName, int carSpeed, String carDirection, String carColor, int carDriveTrain, int carGear)
{
super (carName, carSpeed, carDirection, carColor, carDriveTrain,carGear);
}
The alternative is to add the parameterless constructor to Car, in which case the default constructor of Sub would call that constructor :
public Car()
{
}

Since "Car" has a constructor, any subclass derived from Car needs a constructor as well. So first you need to put a constructor in the Suv class.
Example:
class Suv extends Car {
public Suv() {
super( /* here you need to pass arguments to create a car */);
// any other constructor code
}
}

Add the following constructor to Car:
public Car(){}
The problem is that Suv cannot be created since in order to run Suv's default constructor the constructor of Car needs to be ran first, and Car has only a constructor that accepts arguments so it can't be used as default-constructor.
Another approach would be, as #Markus suggested, to implement a constructor in Suv that'll call super with all the required arguments. Either way, the main idea is that in order to instantiate Suv we need to be able to instantiate Car first otherwise we'll get a compiler error.

What i would suggest is to not put the SUV class in the same file. Instead, Create another class in your current package, name it SUV, extended it and call the superclass constructor by either of the following two syntax:
super(); //calls the superclass no-argument constructor with no parameter list
or
super(parameter list); //calls the superclass constructor with a matching parameter list

Related

Does calling super() from an overloaded class method use variables from non paramaterized method?

After researching a bit I can see that super() is beneficial when a child class extends a parent class.
But what if I have 1 Foo.class with two methods
private variable variable;
private String variable2;
public Foo()
{
this.variable = new variable();
}
and
public Foo(String Paramater)
{
super();
this.variable2 = Paramater;
}
does this work in the sense that the first method is called when using super()
Just to clarify my question.. Can someone explain to me what is happening then in this code?
public ProductDimensions() { }
public ProductDimensions(String sku, String size, double width, double depth, double height, double weight) {
super();
this.sku = sku;
this.size = size;
this.width = width;
this.height = height;
this.depth = depth;
this.weight = weight;
}
Why is super being called when my class doesn't extend anything? is it just useless?
super() in a constructor always calls the matching constructor in the base class. In this case probably java.lang.Object. So in your code, the two constructors have no relation except that they are in the same class.
If you want to chain constructors within the same class, you have to use this() (or the necessary parameters).
super() is used to pass arguments parent class' constructor with matching arguments.
Even if you don't put one, the compiler adds it to the first line of your constructor.
In case of Constructor chaining i.e. calling one constructor from another using this()- matching arguments.
In this case, at least one constructor must call super().
Example of Constructor Chaining:
//Execute multiple constructors in chain
//Advantage: Allocation of multiple type of resources at initialization level. One constructor per resource example: GUI, Database, Network etc.
//Easy Debugging
//We use this() for constructor chaining.
//Can be achieved in any order.
class ConstructorChaining
{
ConstructorChaining()
{
this(10);//always the first line
System.out.println("Default Constructor Completed");
}
ConstructorChaining(int x)
{
this(x,20);//always the first line
System.out.println("X="+x);
System.out.println("Parameter 1 Constructor Completed");
}
ConstructorChaining(int x, int y)
{
// atleast one constructor without this() must be used. - here either you can write super() or compiler will add it for you.
System.out.println("X+Y="+(x+y));
System.out.println("Parameter 2 Constructor Completed");
}
public static void main(String... s)
{
new ConstructorChaining();
}
}

Confusing java code - related to static binding

something about this code confuses me. The first print line is 1600. I understand it has something to do with the static class being Car and not Sportscar. But we created the object as a Sportscar, so why isn't the volume field 3500? Thanks.
public class Car {
public int volume;
public Car() { this(1600); }
public Car(int volume) { this.volume = volume; }
public String toString() { return "Car:" + volume; }
}
public class SportsCar extends Car {
public int volume;
SportsCar() { this(3000); }
SportsCar(int volume) { this.volume = volume; }
public String toString() {return "SportsCar:"+volume;}
}
public class CarApplication {
public static void main(String [] args) {
Car car = new SportsCar(3500);
System.out.println(car.volume);
System.out.println(car.toString());
System.out.println(car);
}
}
First off, note that when you call the constructor for SportsCar Java will automatically call the default constructor for its parent class, Car. This will set the volume field of the object's parent Car class to 1600.
In Java, there is no polymorphism for fields. So whereas the toString() method inside your SportsCar class always overrides that of its parent (Car) class, the rules for how identically named instance variables are accessed is a little different.
If you are accessing volume from within the SportsCar class then the volume of SportsCar will be used. From outside the class itself (so when you're calling from CarApplication) which instance variable is accessed depends upon the compile-time type of the object in question. Because you declare the type of car to be a Car, the volume value of the parent Car class is used--hence 1600 is printed. If you had instead declared car to be a SportsCar, 3500 would be printed.
Another option would be this:
System.out.println(((SportsCar)car).toString());
This will output 3500, since the type of car has been cast to SportsCar.
So the point here is that when you are using car.volume, car variable is of type Car and object reference is of type SportsCar.
As both the classes have the same element named volume and you are trying to refer it through parent object variable, it is returning 1600.
If you will typecast and then check the volume, it will return 3500 as per below code:
System.out.println(((SportsCar)car).volume);
When you declare something in this way:
ParentClass variable = new ChildClass(Args);
The methods and fields in ParentClass are the only ones available to you. It is restricted because you declared the type as a ParentClass. Because Car's volume is 1600 and the object is restricted to the ParentClass's methods and fields, it prints 1600.
An example would be as follows:
Consider I had an Apple Class and a Fruit class:
public class Fruit {
private String type;
public Fruit(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
And the Apple Class:
public class Apple extends Fruit {
private String variant;
public Apple(String variant) {
System.out.println("I like " + variant + apples too!");
super("Apple");
}
public String getVariant() {
return variant;
}
}
And now I instantiate like this:
Fruit ap = new Apple("Fiji");
I don't have access to getVariant() or any methods in the Apple class because the type is of the parent class, not of Apple. I would be able to do getType() but that's it.
In your case:
public class SportsCar extends Car {
public int volume;
SportsCar() {
this(3000);
}
SportsCar(int volume) {
this.volume = volume;
}
public String toString() {
return "SportsCar:"+volume;
}
}
Although SportsCar has it's own constructor and takes it's own volume, the parent class Car is the actual type, causing the Car constructor to be called, hence setting volume to 1600. To specify a SportsCar object, do this:
SportsCar sc = new SportsCar(3500);
System.out.print(sc.toString());
This will print out:
SportsCar:3500
You can also typecast it like so:
Car c = new SportsCar(1600);
System.out.print(((SportsCar) c).toString());
Aman Chhabra answer is right. You created a SportCar object which is from the Car "family". And what you are printing is the volume of Car, not the volume of SportCar.
One other way is to create a SportsCar object instead of Car.
P.s: you should always set your class attributes as private :)

do I need every method in a class to be in the constructor for subclasses to inherit?

So, I have this class that I made, called fighter. I made it work for a minute. Then, I added this method:
private void roll(double block){
block = (int)(Math.random() * 100);
}
This may sound stupid, but do I need to add it to the constructor to inherit the class? I want to do this with a subclass
public void attacked(int baseDamage){
if (human.roll()==block){
return "Nothing happens";
}
else{
a = human.roll();
human.health()-= a;
}
if (human.health > 0){
System.out.println(health);
}
}
So then, do I add roll() to the constructor or is there another way of doing it?
What you can do is use the extend keyword in the subclass, and make the void method, attacked, into a separate class. Now they both will share the exact same methods, and you can still return things to each other.
Another way you can tackle this issue is by again, making those two methods into two separate classes, and nest the subclass underneath the superclass just above the last bracket. If this is part of a larger code you can nest multiple sequences together, or just put multiple methods together. You don't need to add it to the constructor though, the above two reasons were just things you could try which would give you the same answer.
Because you are returning something you don't need to add that method to the constructor!
Well to answer the question
do I need every method in a class to be in the constructor for
subclasses to inherit?
The answer is no. Just call what you want in the constructor. If you want to use a certain method from the subclass, then just make an instance of that class and call the method
Object object = new Object("your constructor info");
object.newMethod.
Is this what your asking ?
subclass inherits all the fields and methods of Super class and you can add the fields/variables and methods to set it. Except for the constructor.
/* Name of the class has to be "Main" only if the class is public. */
public class Fighter {
// the Fighter class has three fields
public int health;
public int attack;
public int speed;
// the Fighter class has one constructor
public Fighter(int health, int attack, int speed) {
this.health = health;
this.attack = attack;
this.speed = speed;
}
// the Figher class has one method, so far...
public void roll(double block){
block = (int)(Math.random() * 100);
}
}
public class Attacker extends Fighter {
// the Attacker subclass adds one field
public int damage;
// the Attacker subclass has one constructor
public Attacker(int damage,
int health,
int attack,
int speed) {
super(health, attack, speed);
this.damage = damage;
}
// the Attacker subclass adds one method
public void attacked(int baseDamage){
// Is human another class , then Fighter or did you mean Figher ?
if (super.roll()==block){
return "Nothing happens";
}
else{
int a = super.roll();
human.health()-= damage;
}
if (super.health > 0){
System.out.println(health);
}
}
}
}
You could also invoke the overridden method through the use of the keyword super.
super.roll();
This better help out ?

Java Subclass Constructor Assigning Values

I'm trying to create an object using a constructor from a subclass but I can't assign values to that object in the subclass Constructor.
Here is the superclass.
public class Bike
{
String color = "";
String type = "";
int age = 0;
public static void main (String [] args)
{
}
public Bike (String s, int i) // Constructor
{
color = s;
age = i;
}
public void PrintBike ()
{
if (type == "")
{
System.out.print(" You didn't give the proper kind of bike.");
}
else
{
System.out.print(" Your bike is a " + type + " bike. \n");
}
}
}
This is the subclass.
public class BikeAdv extends Bike
{
private String type;
public BikeAdv (String color, int age, String BikeType)
{
super (color, age);
type = BikeType;
}
}
Here is the class that calls the constructor.
public class Green
{
public static void main (String [] args)
{
Bike greenBike = new BikeAdv ("Green", 20, "Mountain");
greenBike.PrintBike();
}
}
When I run the class "Green", the output is " You didn't give the proper kind of bike." whereas I would expect to see "Your bike is a Mountain Bike".
Thanks!
The type field in the subclass shadows the type field in the superclass. The field in the superclass is never populated, and that's the one being checked.
If you simply remove the field in the subclass, the assignment there will populate the superclass field, and your code will likely work as you expect.
As noted in other answers though, it would be better to have the fields private or protected according to your need rather than default visibility.
You have declared these attributes without explicit visibility:
String color = "";
String type = "";
int age = 0;
Also, you have type redeclared in BikeAdv, that is probably an error (you don't need to).
If you want to have these attribute only accessible from its class, then you should declared them private. But, in that case, you have to parametrize the constructor to be able to modify all of them. Or maybe create setters for them (be aware that this way you will grant accessibility from outside the class).
private String color = "";
private String type = "";
private int age = 0;
If you want them to be unmodifiable from outside its class, but accessible from its subclasses, then declare them as protected:
protected String color = "";
protected String type = "";
protected int age = 0;
As you can see, there are a lot of possibilities. Check them out here:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
The class Bike is not abstract or an interface, that means that all of it's methods are as they said in the Bike class. When you assign greenBike to be a Bike, not a BikeAdv you tell it to use the methods in the Bike class, instead of the BikeAdv class. Your best bet would be to make Bike abstract and leave the PrintBike void without a body.
Also: you never pass the BikeType String to the super class so there is no way it can receive it.

Difference between 'super' and 'this' [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
this and super in java
I'm new to development. Something that I'm still unable to understand is the difference between this and super keywords. If there are any answers, it would be highly appreciated. Thanks.
this
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
super
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged).
super refers to the base class that the current class extends. this refers to the current class instance.
So, if Parent extends Child and you create a new Child(), super refers to the Parent class (and doing something like super() in the constructor would call the parent's constructor) and this refers to the actual Child instance you created with new.
Super refers to the superclass that a class extends. this refers to the current instance of a class.
These concepts can be confusing for new developers, they will be more clear when you learn about extending classes (inheritance). Sometimes when you refer to a variable or method, you might be being ambiguous for example if you repeated a class variable name in a method, the compiler won't know which variable you are referring to, so you can use this to specify you are referring to the current class's variable (not the local variable). The following would be ambiguous (and WRONG):
class Bike
{
int speed = 10;
public setSpeed(int speed)
{
speed = speed;
}
}
The compiler would have no idea what you intended, and will probably insult you with a cryptic (for a new developer) error message. Using this in the following way tells the compiler "I am referring to the class level variable, NOT the method level variable"
class Bike
{
int speed = 10;
//Constructors and shiz
public void setSpeed(int speed)
{
this.speed = speed;
}
}
(Although in practice you shouldn't duplicate variable names in this way!)
So to summarise, this tells the compiler that you're referring to the CURRENT class. Further ambiguity can arise when you extend classes (inherit functionality for a parent or super class), because the option of overriding the parent method arrises.
class Bike
{
public Bike()
{}
public void printSpeed()
{
System.out.println("This generic bike can go 10 m/s!!");
}
}
Now if we were to extend the bike class by introducing a more specific type of bike, we may want to override the printSpeed method to give the speed of our shiny new bike, like so:
class MountainBike extends Bike
{
public MountainBike() {}
public void printSpeed()
{
System.out.println("WHOAAAH!! MOUNTAIN BIKE GOES 100 m/s!!");
}
public void printGenericSpeed()
{
super.printSpeed();
}
}
The super.printSpeed() tells the compiler to run this method from the parent class, so a call to super.printSpeed() would actually call the printSpeed() method in the Bike class. The following code:
public static void main(String args[])
{
MountainBike mb = new MountainBike();
mb.printSpeed();
mb.printGenericSpeed();
}
will print
WHOAAAH!! MOUNTAIN BIKE GOES 100 m/s!!
This bike can go 10 m/s!!
Note that if we had not overridden the printSpeed() method, calling the following would be a call to the printSpeed() method of the Bike class.
public static void main(String args[])
{
MountainBike mb = new MountainBike();
mb.printSpeed();
}
would print
This bike can go 10 m/s!!
So to conclude, we use this to refer to the current class we're in, and super to refer to the parent of the class we're in.
In Java the keyword this refers to the current object of a class, like in:
class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + "," + y;
}
}
class Point3D extends Point {
public int z = 0;
public Point(int x, int y, int z) {
super(x,y);
this.z = z;
}
public String toString() {
return super.toString() + "," + z;
}
}
In the constructor of the class Point this.x refers to the x defined in the class, where x is the parameter passed into the constructor. Here this is used to resolve the ambiguity of the name x. The same thing is true for y.
In the class Point3D the method toString() uses the return value of the super class Point to produce its own return value.
this: is the reference to the current object in the methods of its class. Refer to any member of the current object through the this keyword.
super: is the derived class' parent when your class extends it through the extend keyword, and you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a protected fields.
this keyword refers to the current instance at that point in time.
super keyword refers to the parent/super class of the current class.
EX:
class Test
{
Test()
{
}
Test(int i)
{
System.out.println("i=" + i);
}
}
class Sample extends Test
{
int i;
void Sample(int i) //constructor
{
this.i=i; // referring class version of the i using 'this'
super(i); // passing parameter to Super/Parent class constructor.
}
}

Categories