Java: Extending a Class [duplicate] - java

This question already has answers here:
Java error: Implicit super constructor is undefined for default constructor
(12 answers)
Closed 8 years ago.
I'm trying to extend my Vehicle class to a HumanPowered class -- Has a field for calories per hour. This is my first time trying to extend a class so I'm a bit confused here.
class Vehicle
{
String description;
String idNumber;
int numWheels;
public Vehicle(String aDescription, String aIdNumber, int aNumWheels)
{
description = aDescription;
idNumber = aIdNumber;
numWheels = aNumWheels;
}
void setDescription (String aDescription)
{
description = aDescription;
}
void setIdNumber (String aIdNumber)
{
idNumber = aIdNumber;
}
void setNumWheels (int aNumWheels)
{
numWheels = aNumWheels;
}
public String getDescription()
{
return description;
}
public String getIdNumber()
{
return idNumber;
}
public int getNumWheels()
{
return numWheels;
}
public String toString()
{
String result= String.format("ID: %s Description: %s Wheels: %d",idNumber,description,numWheels);
return result;
}
}
class humanPowered extends Vehicle
{
int calories;
public humanPowered(String aDescription, String aIdNumber, int aNumWheels, int aCalories) //Error here
{
description = aDescription;
idNumber = aIdNumber;
numWheels = aNumWheels;
calories = aCalories;
}
void setCalories (int aCalories)
{
calories = aCalories;
}
public int getCalories()
{
return calories;
}
public String toString()
{
String result= String.format("ID: %s Description: %s Wheels: %d Calories per Hour: %d",idNumber,description,numWheels, calories);
return result;
}
}
I'm getting an error marked above on my constructor for my humanPowered class saying "Implicit super constructor Vehicle() is undefined. Must explicitly invoke another constructor." I can't figure out where I'm going wrong here. Thanks for any and all help!

Vehicle don't have default constructor hence you have to call its constructor form humanPowered class passing required arguments at the first line of its constructor.
public humanPowered(String aDescription, String aIdNumber, int aNumWheels, int aCalories)
{
super(aDescription,aIdNumber,aNumWheels);
...//other code
}
Points to remember:
Every class have default constructor that is no-argument constructor
If class creates a constructor passing arguments then by default constructor is not created
Each constructor by default calls default constructor of its super-class

Related

Java subclass no arguments

I have a class called "Card"
public class Card
{
private int cardNumber;
private String cardName;
public Card(int cardNumber, String cardName)
{
this.cardNumber = cardNumber;
this.cardName = cardName;
}
public String toString()
{
return cardName;
}
public int getNumber()
{
return cardNumber;
}
}
I'm trying to make a subclass of the Card class called "Ace", but I keep getting the following error whenever I try to compile Ace:
Ace.java:5: error: constructor Card in class Card cannot be applied to given types;
Here's what I have for Ace:
public class Ace extends Card
{
public String isAce;
public Ace()
{
}
public Ace(int cardNumber, String cardName, String isAce)
{
this.cardNumber = cardNumber;
this.cardName = cardName;
this.isAce = "yes";
}
}
I don't understand why I am getting the error when I try to compile Ace. What am I doing wrong?
Card has a constructor (so it doesn't get a default empty constructor). You need to explicitly invoke it in the Ace constructor. Like,
public Ace(int cardNumber, String cardName, String isAce)
{
super(cardNumber, cardName);
this.isAce = "yes";
}
Without an explicit invocation of super() (or this()) the compiler implicitly adds super() (with no arguments). That doesn't work here. Because (as I mentioned) Card already has a non-empty, non-default constructor.

Returns null after accessing variables from Abstract methods

I've got a question about my code. I have class Employee declared as abstract. Under it are 3 abstract methods, abstract String department, abstract int work_days and abstract void print_info.
Now, I created second class Tester that extends the Employee abstract class. I implemented the abstract methods.
abstract class Employee {
abstract String department();
abstract int work_days();
abstract void print_info();
}
class Tester extends Employee{
String dept;
int work_days;
#Override
String department() {
dept = "QA Department";
return dept;
}
#Override
int work_days() {
work_days = 5;
return work_days;
}
#Override
void print_info() {
System.out.println("Department :> " + dept + "Working Days :> " + work_days);
}
}
class Demo {
public static void main(String[] args){
Employee emp_tester = new Tester();
emp_tester.print_info();
}
}
Now, when I create instance for Tester and called print_info from Tester class, the variables dept and work_days returns null and 0.
Did I disobey rules in Abstraction? Any critics are much accepted. Thanks
You have implemented it correct and the values you seeing also correct.
When you have not assigned any values and print them, you get their default values.
For Objects, default is null and for primitives their default. You need to set them before you use them.
class Tester extends Employee{
String dept;
int work_days;
public Tester(String dept, int work_days){
this.dept = dept;
this.work_days = work_days
}
And then while creating a Tester,
Employee emp_tester = new Tester("Testing", 24);
call your department function before printing.
public static void main(final String[] args) {
final Employee emp_tester = new Tester();
emp_tester.department();
emp_tester.work_days();
emp_tester.print_info();
}
Unless you call department() and work_days(), the member variables are not initialized now.
Why don't you add a constructor to initialize members?
Tester() {
dept = "QA Department";
work_days = 5;
}
You are not setting the values of dept or workdays.
You probably want to put lines like dept = "QA Department"; in the constructor of the Tester class, if that is what their values are to be.
You should call the getter insteat of accessing the properties:
class Tester extends Employee{
String dept;
int work_days;
#Override
String department() {
dept = "QA Department";
return dept;
}
#Override
int work_days() {
work_days = 5;
return work_days;
}
#Override
void print_info() {
System.out.println("Department :> " + department() + "Working Days :> " + work_days());
}
Hint: Do not call the methods eqauls to the property names. If a value is returned, call the method get...
class Tester extends Employee{
String dept;
int work_days;
#Override
String getDepartment() {
dept = "QA Department";
return dept;
}
#Override
int getWorkdays() {
work_days = 5;
return work_days;
}
#Override
void print_info() {
System.out.println("Department :> " + getDepartment() + "Working Days :> " + getWorkDays());
}
In Java, default value for type String is null and for type int is 0.
That's why you get dept=null and workdays=0.
As i think you have never initialized the values for the variables it will be null. You have to init the variables by calling department() and work_days() first, before accessing them.
Maybe you need to build a getter construct. This can ensure you that work-days/department will always been set when accessing the getter
Something looking like
int getWorkDays(){
if(work_days == 0){
//work_days(); use this instead of my example to call the overriden abstract method
work_days = 5;
}
return work_days;
}
You can also write a getter for the Dept:
String getDept(){
if(dept == null || dept.equals("")){
//department(); use this instead of my example to call the overriden abstract method
dept= "QA Department";
}
return dept;
}
This getters should be used everywhere now like:
#Override
void print_info() {
System.out.println("Department :> " + getDept() + "Working Days :> " + getWorkDays());
}
You can also call the methods to initialize the values in your Constructor like:
Tester(){
work_days();
department();
}
Once you will call method ,
String department()
int work_days()
with the same object , then only your property will get initilize. else, you need to initialize either using Constructor / SIB / IIB. Then after , you can call print_info() method to get the value displayed.

get parameter modifier reflection

I have a SimplePojo class and I would like to retrieve parameter modifier at run-time using reflection.
However, it does not seem to work ... SSCEE
public final class SimplePojo {
private final String name;
private final int age;
public SimplePojo(String name, final int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setAge(int age) {
}
public int getAge() {
return age;
}
}
And this is how I try to check if parameter modifier is FINAL
for (Class<?> paramClazz : method.getParameterTypes()) {
if (!Modifier.isFinal(paramClazz.getModifiers())) {
throw new ConstraintViolationException(
String.format("Parameters of method '%s' in '%s' must be declared as 'final'",
method.getName(),
point.getTarget().getClass().getCanonicalName()
)
);
}
}
EDIT:
//are all constructors params final
for (Constructor constructor : clazz.getConstructors()) {
for (Class<?> constructorParam : constructor.getParameterTypes()) {
Log.e(TAG, "constructorParam:" + constructorParam.getName() + ", mod: " + constructorParam.getModifiers());
if (!Modifier.isFinal(constructorParam.getModifiers())) {
throw new ConstraintViolationException(
String.format("Constructor parameters in '%s' annotated with '%s'" +
" must be declared as 'final'",
clazz.getCanonicalName(),
Inmutable.class.getSimpleName()
)
);
}
}
}
and output:
constructorParam:java.lang.String, mod: 17
constructorParam:int, mod: 1041
Assuming you are using Java 8, you can use the Executable.getParameters() method to get the formal parameters of a Method.
This returns an array of Parameter instances, on which you can invoke Parameter.getModifiers().
I don't believe there is a standard pre-Java 8 solution.
getModifiers returns a set of flags.
Try this:
final int FINAL = 0x0010;
if (!(paramClazz.getModifiers() & FINAL)) {
throw new ...

Java - calling on constructor- Compiler error

Here is my field.java class. Ive got the public Field(String name, int number) defined here.
public class Field
{
String name;
int number;
public Field(String name, int number){
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
#Override
public String toString() {
return "Field{" + "name=" + name + ", number=" + number + '}';
}
}
Here is my Player.java class, Im getting an error on my Field currentField = new Field(); - it says that my Field is not defined as a constructor in my Field.java class
public class Player
{
private String name;
private int pos;
Field currentField = new Field();
public Player()
{
}
}
Anyone got a suggestion on why Im throwing errors?
You have provided a parameterized constructor in your class
public Field(String name, int number){
this.name = name;
this.number = number;
}
And hence no default (no-arg) constructor is provided when you define a parametrized constructor.
So when you are trying to create an instance using Field currentField = new Field();, it cannot compile since there is no matching constructor.
Solutions you can try:
1.
Add a no-arg constructor to your class :
public Field()
{
}
Or
2.
While creating an instance, pass values to constrcutor :
Field currentField = new Field("abc", 123);
Yes because your class receiving two arguments name and number and you are trying to create instance of it without passing them.
Either you can pass them
Field currentField = new Field("test", 1); // for ex :
or create a default no arg constructor to your Field class.
/** default no arg constructor **/
public Field(){
// TODO : when there is no param
}
Field currentField = new Field();
You are not passing any arguments to the constructor. You will either need to provide a name and number as parameters, or define a default constructor :
public Field(String name, int number){
this.name = name;
this.number = number;
}
Field currentField = new Field("fieldName", 1);
or
public Field(){
this.name = "";
this.number = 0;
}
Field currentField = new Field();
In every Java class there is a default constructor, if you add any other constructor it will override the default constructor. So to make your code work you have to add no argument constructor.
public Field(){
}

Use of "this" keyword in java [duplicate]

This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 7 years ago.
I was studying method overriding in Java when ai came across the this keyword. After searching much about this on the Internet and other sources, I concluded that thethis keyword is used when the name of an instance variables is same to the constructor function
parameters. Am I right or wrong?
this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):
class Foo
{
private int bar;
public Foo() {
this(42); // invoke parameterized constructor
}
public Foo(int bar) {
this.bar = bar; // disambiguate
}
public void frob() {
this.baz(); // used "just because"
}
private void baz() {
System.out.println("whatever");
}
}
this keyword can be used for (It cannot be used with static methods):
To get reference of an object through which that method is called within it(instance method).
To avoid field shadowed by a method or constructor parameter.
To invoke constructor of same class.
In case of method overridden, this is used to invoke method of current class.
To make reference to an inner class. e.g ClassName.this
To create an object of inner class e.g enclosingObjectReference.new EnclosedClass
You are right, but this is only a usage scenario, not a definition. The this keyword refers to the "current object". It is mostly used so that an object can pass itself as a parameter to a method of another object.
So, for example, if there is an object called Person, and an object called PersonSaver, and you invoke Person.SaveYourself(), then Person might just do the following: PersonSaver.Save( this );
Now, it just so happens that this can also be used to disambiguate between instance data and parameters to the constructor or to methods, if they happen to be identical.
this keyword have following uses
1.used to refer current class instance variable
class Student{
int id;
String name;
student(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
here parameter and instance variable are same that is why we are using this
2.used to invoke current class constructor
class Student{
int id;
String name;
Student (){System.out.println("default constructor is invoked");}
Student(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan");
e1.display();
e2.display();
}
}
3.this keyword can be used to invoke current class method (implicitly)
4.this can be passed argument in the method call
5.this can be passed argument in the constructor call
6.this can also be used to return the current class instance
This refers current object. If you have class with variables int A and a method xyz part of the class has int A, just to differentiate which 'A' you are referring, you will use this.A. This is one example case only.
public class Test
{
int a;
public void testMethod(int a)
{
this.a = a;
//Here this.a is variable 'a' of this instance. parameter 'a' is parameter.
}
}
Generally the usage of 'this' is reserved for instance variables and methods, not class methods ...
"class methods cannot use the this keyword as there is no instance for
this to refer to..."
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Here's a trivial example ...
public class Person {
private String name;
private int age;
private double weight;
private String height;
private String gender;
private String race;
public void setName( String name ) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAge( int age) {
this.age = age;
}
public int getAge(){
return this.age;
}
public void setWeight( double weight) {
this.weight = weight;
}
public double getWeight() {
return this.weight;
}
public void setHeight( String height ) {
this.height = height;
}
public String getHeight() {
return this.height;
}
public void setGender( String gender) {
this.gender = gender;
}
public String getGender() {
return this.gender;
}
public void setRace( String race) {
this.race = race;
}
public String getRace() {
return this.race;
}
public void displayPerson() {
System.out.println( "This persons name is :" + this.getName() );
System.out.println( "This persons age is :" + this.getAge() );
System.out.println( "This persons weight is :" + this.getWeight() );
System.out.println( "This persons height is :" + this.getHeight() );
System.out.println( "This persons Gender is :" + this.getGender() );
System.out.println( "This persons race is :" + this.getRace() );
}
}
And for an instance of a person ....
public class PersonTest {
public static void main( String... args ) {
Person me = new Person();
me.setName( "My Name" );
me.setAge( 42 );
me.setWeight( 185.00 );
me.setHeight( "6'0" );
me.setGender( "Male" );
me.setRace( "Caucasian" );
me.displayPerson();
}
}
In case of member variable and local variable name conflict, this key word can be used to refer member variable like,
public Loan(String type, double interest){
this.type = type;
this.interest = interest;
}
if you have knowladge about c,c++ or pointers, in that language this is a pointer that points object itself. In java everything is reference. So it is reference to itself in java. One of the needs of this keyword is that:
Think that this is your class
public class MyClass
{
public int myVar;
public int myMethod(int myVar)
{
this.myVar = myVar; // fields is set by parameter
}
}
If there is not this keyword you it is confused that this is paramter or class field.When you use this.myVar it refers field of this object.
I would like to modify your language. The this keyword is used when you need to use class global variable in the constructors.
public class demo{
String name;
public void setName(String name){
this.name = name; //This should be first statement of method.
}
}
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.
One more thing that should be in mind is that this keyword might be the first statement of your method.
This is used in java. We can use in inheritance & also use in method overloading & method overriding. Because the actual parameter or instance variable name has same name then we can used this keyword complsary . But some times this is not same as when we can not use this keyword complsary.....
Eg:- class super
{
int x;
super(int x)
{
this.x=x
}
}

Categories