OOP: inheritance with extends - java

Can anybody tell me why this code isn't correct?
public class Boss extends Angestellter {
Boss(String v, String n, int a) { // ERROR **
vorname = großKleinSchreibung(v);
nachname = großKleinSchreibung(n);
alter = a;
}
}
** Implicit super constructor Angestellter() is undefined. Must explicitly invoke another constructor
public class Angestellter {
protected String vorname;
protected String nachname;
public int alter;
Angestellter(String v, String n, int a) {
this.vorname = großKleinSchreibung(v);
this.nachname = großKleinSchreibung(n);
this.alter = a;
}
I dont find the error, because its exactly how its explained in the book which im using to learn oop with java.

You should call the constructor of the base class explicitly, since if you don't, the compiler adds an implicit call to the parameterless constructor of the base class, which doesn't exist in your case.
public class Boss extends Angestellter {
Boss(String v, String n, int a) {
super (v,n,a);
vorname = großKleinSchreibung(v);
nachname = großKleinSchreibung(n);
alter = a;
}
}

In simple words
You cannot override constructor of super class in JAVA
Here is your little modified code !!
public class Angestellter {
protected String vorname;
protected String nachname;
public int alter;
Angestellter(String v, String n, int a) {
this.vorname = großKleinSchreibung(v);
this.nachname = großKleinSchreibung(n);
this.alter = a;
}
...
}
public class Boss extends Angestellter {
... Other methods
}
// In main
Angestellter myObj = new Boss("asd","as",1); // It will call constructor itself ... because it is inherited !!

Related

how to define parameterized constructor of abstract class in child class in java

how to define parameterized constructor of abstract class in child class in java
abstract class Car {
protected boolean isSedan;
protected String seats;
public Car(boolean isSedan, String seats) {
this.isSedan = isSedan;
this.seats = seats;
}
public boolean getIsSedan() {
return this.isSedan;
}
public String getSeats() {
return this.seats;
}
abstract public String getMileage();
}
public class WagonR extends Car{
protected int mileage;
protected boolean isSedan;
public WagonR(int mileage) {
super(isSedan,seats);
this.mileage=mileage;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int carType = Integer.parseInt(bufferedReader.readLine().trim());
int carMileage = Integer.parseInt(bufferedReader.readLine().trim());
Car wagonR = new WagonR(carMileage);
wagonR.printCar("WagonR");
}
}
While passing isSedan and seats parameters in super block in WagonR constructor, getting compilation error "Cannot refer to an instance field isSedan while explicitly invoking a constructor" and "Cannot refer to an instance field seats while explicitly invoking a constructor"
Constraint is while execution only one parameter will be passed like WagonR(carMileage).
I was doing mistake by passing parameter names in super block rather than passing parameter values using which I wanted to invoke Car constructor.
//incorrect
public WagonR(int mileage) {
super(isSedan,seats);
this.mileage=mileage;
}
//correct
public WagonR(int mileage) {
super(false,"4");
this.mileage=mileage;
}
Your WagonR class shoud be like this:
public class WagonR extends Car{
protected int mileage;
protected boolean isSedan;
public WagonR(int mileage) {
super(false, "4");
this.mileage=mileage;
}
public WagonR(int mileage, boolean isSedan, String seats) {
super(isSedan, seats);
this.mileage=mileage;
}
// And don't forget override method
#Override
public String getMileage() {
}
}

howto handle objects of private class, got as parameter

I learn Java at university and I have to do following excercise.
(simplified example)
import java.util.*;
public class A{
private static class B{
Integer b;
private B(int b){this.b = b;}
}
private static class B_Comparable extends B implements Comparable<B_Comparable> {
private B_Comparable(int b){super(b);}
#Override
public int compareTo(B_Comparable that) {
return this.b.compareTo(that.b);
}
}
private static class C<T> implements myList<T> { // see below
private ArrayList<T> lst = new ArrayList<>();
private static C<B_Comparable> createComparable() {
C<B_Comparable> ust = new C<B_Comparable>();
for (int i =0; i < 9; i++)
ust.lst.add(new B_Comparable(i));
return ust;
}
#Override
public T fetch(int index){
return lst.get(index);
}
}
private void test(){
C<B_Comparable> ustComparable = C.createComparable();
A result = ClassD.handle(ustComparable,3,4);
}
}
//--------------------------------------------------------
public class ClassD{
public static <T, S> T handle( S ustC, int pos1, int pos2 ){
// how can I compare elems of object ustC ?
ustC.fetch(pos1).compareTo(ustC.fetch(pos2));
//how can I fetch obj at pos1 ?
return ustC.fetch(pos1);
}
}
//-----------------------------------------
public interface myList<T> {
T fetch(int index);
}
static method handle gets an object (ustC) which is private. How can I
use methods, compareTo and fetch for this object? I have tried parametrisation, but if its the right way, I don't know how to solve.
Thanks for any help.
As discussed in comments, ustC, by virtue of the way handle is called in this context is of type C, which implements the myList interface. This interface exposes the fetch method, and is visible to your handle method.
The modification you arrived at in your comments would allow you to call fetch:
//Solution
public class ClassD {
public static <S extends Comparable> S handle(myList<S> ustC, int pos1, int pos2 ){
int y = ustC.fetch(pos1).compareTo(ustC.fetch(pos2));
return ustC.fetch(pos1);
}
}

JNA callback function with pointer to structure argument

I am busy with a project in which I have to do native calls to a proprietary C library. I came across JNA, which seems to be tried and tested with a number of successful projects.
I am having trouble passing a structure (or pointer to) through to a callback function. I have tried many different scenarios before, and basically, any structure member that requires memory allocation, like a String (char *), for instance, is null when I retrieve it.
I have tried to illustrate the problem with the following example:
C code:
typedef struct {
int number;
char *string;
} TEST_STRUCT;
typedef union {
int number;
TEST_STRUCT test_struct;
} TEST_UNION;
typedef void (*TEST_CB)(TEST_UNION*);
void test(TEST_CB test_cb)
{
TEST_STRUCT *test_struct = malloc(sizeof *test_struct);
test_struct->number = 5;
test_struct->string = "Hello";
TEST_UNION *test_union = malloc(sizeof *test_union);
test_union->number = 10;
test_union->test_struct = *test_struct;
test_cb(test_union);
free(test_struct);
free(test_union);
}
Java-code:
public interface TestLib extends Library
{
class TestStruct extends Structure
{
public int number;
public String string;
public TestStruct() {
super();
}
protected List<? > getFieldOrder() {
return Arrays.asList("number", "string");
}
public TestStruct(int number, String string) {
super();
this.number = number;
this.string = string;
}
public TestStruct(Pointer peer) {
super(peer);
}
public static class ByReference extends MBTStatus implements Structure.ByReference {}
public static class ByValue extends MBTStatus implements Structure.ByValue {}
}
class TestUnion extends Union {
public int number;
public TestStruct testStruct;
public TestUnion() {
super();
}
public TestUnion(int number, TestStruct testStruct) {
super();
this.number = number;
this.testStruct = testStruct;
}
public TestUnion(Pointer pointer) {
super(pointer);
}
public static class ByReference extends TestUnion implements com.sun.jna.Structure.ByReference {}
public static class ByValue extends TestUnion implements com.sun.jna.Structure.ByValue {}
}
interface TestCallback extends Callback
{
public void callback(TestUnion testUnion);
}
void test(TestCallback testCallback);
}
The main Java class:
public class TestMain
{
static
{
System.loadLibrary("test");
}
public static void main (String [] args)
{
TestLib.INSTANCE.test(
new TestLib.TestCallback()
{
public void callback(TestLib.TestUnion testUnion)
{
System.out.println(testUnion.testStruct.string == null ? "The string value is null" : "The string value is: " + testUnion.testStruct.string);
}
}
);
}
}
The string value is then null:
The string value is null
I am a complete noob when it comes to JNA, so I have lots to learn. I'm not sure if the mapping of the structure is correct, which might be the cause of the null value.
Any help will be greatly appreciated!
EDIT: I made the question a bit more interesting:
So the argument to a callback function is a union, instead of a struct. The struct is now part of the union. When I do it this way, the value of the struct string variable seems to be null as well.
I just found the answer to the updated question myself. This example ultimatley shows how to do it. As a union only takes up the memory of its largest member, its type has to be set to that member. The Union.read() function must then be called to read the "selected" variable. This is done as follows:
testUnion.setType(TestLib.TestStruct.class);
testUnion.read();
The testStruct variable can then be accessed. The correct callback function is then:
public void callback(TestLib.TestUnion testUnion)
{
testUnion.setType(TestLib.TestStruct.class);
testUnion.read();
System.out.println(testUnion.testStruct.string == null ? "The string value is null" : "The string value is: " + testUnion.testStruct.string);
}
It might be useful when you implement the Union's Pointer-based constructor to invoke read after calling super, and override read() so that it always does the right thing, e.g.
class MyStructure1 {
public int type;
public int intField;
}
class MyStructure2 {
public int type;
public float floatField;
}
class MyUnion extends Union {
public int type;
public MyStructure1 s1;
public MyStructure2 s2;
public MyUnion(Pointer p) {
super(p);
read();
}
protected void read() {
int type = getPointer().getInt(0);
switch(type) {
case 0: setType(MyStruct1); break;
case 1: setType(MyStruct2); break;
}
super.read();
}
}
JNA will generally try to auto-populate as much data as it can if the union's type has not been set, avoiding any pointer fields (like strings) which might result in memory faults if they contain invalid data.

Inherited methods not found in Eclipse

I'm doing semantic analysis of java codes. Some classes are as below:
ClassOrInterfaceDeclaration -> TypeDeclaration -> BodyDeclaration -> Node
The Node class is like this:
public abstract class Node {
private final int beginLine;
private final int beginColumn;
private Scope enclosingScope;
#Deprecated
public Node(int line, int column) {
this.beginLine = line;
this.beginColumn = column;
this.endLine = line;
this.endColumn = column;
}
public Node(int beginLine, int beginColumn, int endLine, int endColumn) {
this.beginLine = beginLine;
this.beginColumn = beginColumn;
this.endLine = endLine;
this.endColumn = endColumn;
}
public void setMyScope(Scope enclosingScope) {
this.enclosingScope = enclosingScope;
}
public Scope getMyScope() {
return enclosingScope;
}
public final int getBeginLine() {
return beginLine;
}
public final int getBeginColumn() {
return beginColumn;
} ... ...
Now, when I call these methods from an instance of ClassOrInterfaceDeclaration, any method is available except the setMyScope() and getMyScope(). Kinda a newbie. No idea why and how to fix it.
Codes of ClassOrInterfaceDeclaration is as below:
public final class ClassOrInterfaceDeclaration extends TypeDeclaration {
private final List<AnnotationExpr> annotations;
private final boolean isInterface;
private final List<TypeParameter> typeParameters;
private final List<ClassOrInterfaceType> extendsList;
private final List<ClassOrInterfaceType> implementsList;
public ClassOrInterfaceDeclaration(int line, int column, JavadocComment javaDoc, int modifiers, List<AnnotationExpr> annotations, boolean isInterface, String name, List<TypeParameter> typeParameters, List<ClassOrInterfaceType> extendsList, List<ClassOrInterfaceType> implementsList, List<BodyDeclaration> members) {
super(line, column, javaDoc, name, modifiers, members);
this.annotations = annotations;
this.isInterface = isInterface;
this.typeParameters = typeParameters;
this.extendsList = extendsList;
this.implementsList = implementsList;
}
public List<AnnotationExpr> getAnnotations() {
return annotations;
}
public boolean isInterface() {
return isInterface;
}
public List<TypeParameter> getTypeParameters() {
return typeParameters;
}
public List<ClassOrInterfaceType> getExtends() {
return extendsList;
}
public List<ClassOrInterfaceType> getImplements() {
return implementsList;
}
#Override
public <A> void accept(VoidVisitor<A> v, A arg) {
v.visit(this, arg);
}
#Override
public <R, A> R accept(GenericVisitor<R, A> v, A arg) {
return v.visit(this, arg);
}
}
TypeDeclaration and BodyDeclaration is similar. There is nothing about line, column or scope in them. However, while beginLine() and beginColumn() work well, the setMyScope(), getMyScope() don't. The latter two methods were added by me. I suspect that I have done something silly but can't figure out.
It seems like an issue where you are not able to reference the latest class version.
Possible issues :
code is not recompiled at all
there may be compilation error in other classes in the same src. Fix those and compile again.
You may have the jar file path in your classpath where the jar is not getting replaced with the latest one.
Please check if all these boxes are ticked. If the issue still persists, let us know

Using a Custom-Defined Comparator in a Constructor

I'm having difficulty using Comparators in Constructors. When I try the following code:
InsertionSorter is = new InsertionSorter(bookList.toArray(new Comparable[bookList.size()]), new GenreComparator(), SortType.ASC);
I get this error:
no suitable constructor found for InsertionSorter(java.lang.Comparable[],sort.GenreComparator,sort.SortType)
constructor sort.InsertionSorter.InsertionSorter(java.lang.Comparable[],java.util.Comparator<java.lang.Object>,sort.SortType) is not applicable
(actual argument sort.GenreComparator cannot be converted to java.util.Comparator<java.lang.Object> by method invocation conversion)
constructor sort.InsertionSorter.InsertionSorter(java.lang.Comparable[],sort.SortType) is not applicable
(actual and formal argument lists differ in length)
Here are the useful code snippets:
AbstractSorter.java:
abstract class AbstractSorter {
protected Comparable[] values;
protected Comparator<Object> cmp;
protected SortType st;
protected abstract void doSort();
protected AbstractSorter(Comparable[] init, SortType type) {
values = new Comparable[init.length];
System.arraycopy(init, 0, values, 0, init.length);
cmp = null;
st = type;
}
protected AbstractSorter(Comparable[] init, Comparator<Object> comp, SortType type) {
values = new Comparable[init.length];
System.arraycopy(init, 0, values, 0, init.length);
cmp = comp;
st = type;
}
public Comparable[] getValues() {
return values;
}
}
class InsertionSorter extends AbstractSorter {
public InsertionSorter(Comparable[] init, SortType type) {
super(init, type);
}
public InsertionSorter(Comparable[] init, Comparator<Object> comp, SortType type) {
super(init, comp, type);
}
#Override
public void doSort() {
// sorts values
}
}
enum SortType {ASC, DSC};
Book.java:
public class Book implements Cloneable, Comparable<Book> {
private Person author; // implementation details of Person don't matter here
private String title, isbn;
private int year;
private BookGenre genre;
public Book(Person authorInit, String titleInit, String isbnInit,
int yearInit, BookGenre genreInit) {
author = authorInit;
title = titleInit;
isbn = isbnInit;
year = yearInit;
genre = genreInit;
}
#Override
public String toString() {
return author.toString() + " " + title + " " + isbn + " " + year
+ " " + genre;
}
#Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
#Override
public int compareTo(Book other) {
return author.compareTo(other.author);
}
public Person getAuthor() {
return author;
}
public String getTitle() {
return title;
}
public String getIsbn() {
return isbn;
}
public int getYear() {
return year;
}
public BookGenre getGenre() {
return genre;
}
}
class TitleComparator implements Comparator<Book> {
#Override
public int compare(Book a, Book b) {
return a.getTitle().compareToIgnoreCase(b.getTitle());
}
}
class GenreComparator implements Comparator<Book> {
#Override
public int compare(Book a, Book b) {
return a.getGenre().compareTo(b.getGenre());
}
}
enum BookGenre { COMIC, MYSTERY, SCIENCE, TRAVEL };
EDIT Thanks to Rohit for a solution to this problem, but now I'm having a related problem. In the method doSort(), I have the code snippet
cmp.compare(values[j-1], values[j])
(don't worry, I have checks in place to make sure this isn't called if cmp == null. This gives the following error:
method compare in interface java.util.Comparator<T> cannot be applied to given types;
required: capture#1 of ? extends java.lang.Object,capture#1 of ? extends java.lang.Object
found: java.lang.Comparable,java.lang.Comparable
reason: actual argument java.lang.Comparable cannot be converted to capture#1 of ? extends java.lang.Object by method invocation conversion
Note that I have changed the above in AbstractSort.java to replace Comparable<Object> with Comparable<? extends Object>
GenreComparator class implements Comparator<Book>. So you can't pass an instance of that class where a Comparator<Object> is required. Both are non-compatible.
You can however change Comparator<Object> to Comparator<? extends Object> in your constructor, and also the type of field cmp in AbstractSorter class.

Categories

Resources