I am a beginner java programmer learning step by step how to code with Java.
I have this code that is an implementation of an interface in java.
Please assist me in debugging it.
Here is the interface:
package ke.munyiri.me;
public interface Hp {
public void scrollUp (int increment);
public void scrollDown (int decrement);
public void rightClick();
public void leftClick ();
}
and here is its implementation:
/**
*
*/
package ke.munyiri.me;
/**
* #author MUNYIRI
*
*/
public abstract class Mouse implements Hp {
char manufacturer;
char type;
static int scroll;
boolean click;
public static void main(String[] args){
public void scrollUp(int increment){
scroll = scroll + increment;
System.out.println("The mouse is scrolling up");
}
public void scrollDown (int decrement){
int scrollDown = scroll - decrement;
System.out.println("The mouse is scrolling down");
}
public void rightClick(){
boolean rightClick = true;
System.out.println("The mouse is right Clicking");
}
public leftClick(){
boolean leftClick = true;
System.out.println("The mouse is left Clicking");
}
}
}
You have compile errors in your code. You can't declare methods inside a another method. In your code You have override interface methods inside your main method. Take them out of the main method scope. Like this
public abstract class Mouse implements Hp {
char manufacturer;
char type;
static int scroll;
boolean click;
public static void main(String[] args){
}
public void scrollUp(int increment){
scroll = scroll + increment;
System.out.println("The mouse is scrolling up");
}
public void scrollDown (int decrement){
int scrollDown = scroll - decrement;
System.out.println("The mouse is scrolling down");
}
public void rightClick(){
boolean rightClick = true;
System.out.println("The mouse is right Clicking");
}
public void leftClick(){
boolean leftClick = true;
System.out.println("The mouse is left Clicking");
}
}
There are issues in your code. You can't declare another method inside a method.
Change your structure
public MyClass implements MyInterface{
public static void main(String[] args){
}
public void myMethod1(){
}
}
So you defined an Interface and an abstract class but no concrete class. Your implementation can't be used on it's own but requires a further 'implementation' class or you could remove the abstract keyword from your class definition. This keyword isn't needed as you don't have any abstract methods in your class.
Well and as others have pointed out, your main method (which you don't need) misses it's closing bracket.
Before Learning the concept of interface , You should have to learn basic . i.e you cannot have methods implemented inside another method, And to Know about interface first you should have knowledge about what is Abstract and Concrete.
ABSTRACT CLASS
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation.
CONCRETE CLASS
An abstract class is meant to be used as the base class from which other classes are derived. The derived class is expected to provide implementations for the methods that are not implemented in the base class. A derived class that implements all the missing functionality is called a concrete class .
public class Graph implements GraphicObject{
public void draw()
{
//defination
}
Related
I have a method sleep() which sets int hp of the instance to final int MAX_HP. I have placed this method inside the Warrior and Mage classes, which are the child classes of Character. The problem here is that I define MAX_HP individually within each child class as Warrior's and Mage's would have different Max_HP's, so it seems like I have to also declare sleep() within each class instead of just once in the parent class - inefficient. Is there a way I can declare the sleep method in the parent class and somehow retrieve the MAX_HP's from within the child classes? Or is there a better way to do this?
//Warrior Class
public class Warrior extends Adventurer{
private final int MAX_HP = 150;
public void sleep(){
setHp(MAX_HP);
System.out.println(getName() + "fully restored HP!");
}
}
//Mage Class
public class Mage extends Adventurer{
private final int MAX_HP = 100;
public void sleep(){
setHp(MAX_HP);
System.out.println(getName() + "fully restored HP!");
}
}
//Adventurer Class
public abstract class Adventurer{
private int hp;
public Adventurer(int hp){
this.hp = hp;
}
public int getHp(){
return this.hp;
}
public void setHp(int hp){
this.hp = hp;
}
Yes, you can.
Inside the abstract class Adventurer add an abstract method:
public abstract int getChildHP();
and have Warrior and Mage implement it:
public int getChildHP() { return MAX_HP };
(MAX_HP is different for each one of them of course).
Move the sleep() method (delete it from the children) to the abstract class and implement it:
public void sleep() {
setHp(getChildHP());
System.out.println(getName() + "fully restored HP!");
}
When this method is called, the relevant getChildHP() will be called according to the instance.
Now sleep() exists only once in the parent class ==> no code duplication.
Hope it helps.
I have one super class, which called game that. It looks like this:
import java.util.ArrayList;
public class Game {
private ArrayList<Enemy> enemies = new ArrayList<Enemy>();
private ArrayList<Tower> towers = new ArrayList<Tower>();
private int corridorLength;
private int currentPosition = 0;
public Game(int corridorLength){
this.corridorLength = corridorLength;
}
public void addTower(int damage,int timeStep){
this.towers.add(new Tower(damage,timeStep)); // Add tower with
current position corrdor length
}
public void addEnemy(int health, int speed){
this.enemies.add(new Enemy(health,speed));
}
public void advance(){
this.currentPosition = this.currentPosition + 1;
if(this.currentPosition == this.corridorLength){
System.out.println("Game Over");
}
}
public void printDamage(){
System.out.println(this.towers.get(this.currentPosition));
}
}
The main focus is on the public void addTower(int, int)
So, I have a subclass called Tower:
public class Tower extends Game {
public Tower(int damage, int timeStep){
super.addTower(damage,timeStep);
}
public void getDamage(){
super.printDamage();
}
}
And subclass of the Tower subclass called Catapult:
public class Catapult extends Tower {
public Catapult(){
super(5,3);
}
}
I am new to Java and can't see what am I doing wrong here. Why do I need a default constructor for the Tower in the Game?
You need to explicitly declare default constructor in Game class.
public Game (){}
Since, Object instantiation chained to Object class during that, it will call its super class constructor. You have explicitly declared arg-constructor in Game, so default constructor won't be added automatically.
I'm taking a tutorial on building a simple behavior Ai. It's 'brain' class is abstract and contains states as in "running","success","failure". Now in the my ai unit - droid class i have a method to start the brain of the droid up.
public void update(){
if(Routine.getState()==null){
Routine.start();
}
Routine.act(this, board);
}
Now this isn't possible in java because it's a static reference to a non-static method.
The routine abstract class that i'm trying to reference to here goes like this :
public abstract class Routine {
public enum RoutineState{
Success,
Failure,
Running
}
protected RoutineState state;
protected Routine() { }
public void start(){
this.state = RoutineState.Running;
}
public abstract void reset();
public abstract void act(droid droid, board board);
public void succed(){
this.state = RoutineState.Success;
}
public void Fail(){
this.state = RoutineState.Failure;
}
public boolean isSuccess(){
return state.equals(RoutineState.Success);
}
public boolean isFailure(){
return state.equals(RoutineState.Failure);
}
public boolean isRunning(){
return state.equals(RoutineState.Running);
}
public RoutineState getState(){
return state;
}
}
I've tried copying the method to one of the classes that extends the Routine, but that doesn't work either the same problem comes up.
The static requirement is especially difficult on start() and act() that contain this. and are initializers.
I can only make the method update() like it is, in the routine where i initialize the droid and the board it will be acting on - but i don't see this quite like the solution i'd like to have.
For sure, you can reference an abstract class and call its abstract classes, but the object you exactly reference should be an extender of the abstract class.
For example, create a list of different objects, all extending one abstract class.
public abstract class ExAbstract { public abstract void abstractmethod() {...} }
public class ExampleA extends ExAbstract { #Override... }
public class ExampleB extends ExAbstract { #Override... }
...
List<ExAbstract> list = new ArrayList<>();
list.add(new ExampleA());
list.add(new ExampleB());
...
And then, you can call abstract method on it.
for (ExAbstract test : list){
test.abstractmethod();
}
(Or Java 8)
list.forEach(ExAbstract::abstractmethod);
But if object wasn't extending abstact, and it was abstract itself, it would give an error.
EDIT: In your case, with Routine class, you should make a constructor for it, and then make a new object. (I see you have a constructor already...) If you want to use a method without creating an object, use static
In Routine.java:
public Routine(ExampleArg a){
this.a = a;
}
In your Routine call:
Routine r = new Routine(a);
r.start();
I have multiple different implementations of an object, which implement this custom interface I made called Board.
Board contains a method that looks like the following
public void ConvertFromString(String formattedString);
Each object implementing Board calls ConvertFromString() in its constructor.
Looks like the following.
public void BoardImpl1 implements Board
{
public Board(string B)
{
ConvertFromString(b);
}
public void ConvertFromString(String formattedString)
{
//do some parsing on string and set up the BoardImpl properties
}
}
ConvertFromString being public causes a warning, so one of the workarounds that I found would be to make BoardImpl final. Is there a better way to approach this?
//do some parsing on string and set up the BoardImpl properties
The method should be responsible to convertFromString only.
1) Make the method final
public class BoardImpl implements Board{
public void final convertFromString(String formattedString)
{
//do some parsing on string and set up the BoardImpl properties
}
}
2) Solution make an abstract class and call in superClass constructor so you don't have to call in each subclass BUT don't use properties from subclass cause they aren't intilized.
public abstract class AbstractBoard implements Board{
public AbstractBoard(String s){
convertFromString(s);
}
}
3) And My preferred one make something with composition
public class Client {
private Board board;
public Client(String s){
board.convertFromString(s);
}
public void setBoard(Board board){
this.board = board;
}
}
Then in the board you can delegate responsability of deciding wich Board you should use to a factory or if it has no state a FlyweightFactory
Does ConvertFromString really belong in the Board interface to begin with? What if you had a board that initialized its properties a different way? I would consider refactoring out the board class if you can.
public class Board {
public Board(Properties properties) {...}
}
I think the reason you're having trouble setting this up without calling the public ConvertFromString method is because the design is a little off. The ConvertFromString makes assumptions about the implementation of it.
There is compile error in your code
I could not get a compile warning with following code
public interface Board {
public void ConvertFromString(String formattedString);
}
public class BoardImpl1 implements Board {
public BoardImpl1(String b) {
ConvertFromString(b);
}
public void ConvertFromString(String formattedString) {
//bla bla
}
}
I'm confused with polymorphism and I'm wondering if this is consider polymorphism?
I feel it looks kind of weird but it still compiles correctly.
public class Family {
void FamilyInfo() {
System.out.println("This is a family super class");
}
}
public class Grandparents extends Family {
void FamilyInfo() {
System.out.println("Graparents are the elders in the family and they are the sub class of family");
}
}
public class Parents extends Grandparents {
void FamilyInfo() {
System.out.println("The parents are the children of the grandparents and they are the sub sub class for family");
}
}
public class FamilyDemo {
public static void main(String ary[]) {
Grandparents Gp = new Grandparents();
Parents P1 = new Parents();
Gp.FamilyInfo();
P1.FamilyInfo();
}
}
Your method FamilyInfo is being overridden in all three classes in the hierarchy. This is one example of polymorphism.
When you call Gp.FamilyInfo();: It will call the method implemented in Grandparents class and print Graparents are the elders in the family and they are the sub class of family while P1.FamilyInfo(); will call the method in Parents class and print The parents are the children of the grandparents and they are the sub sub class for family.
Thus you can see that same method FamilyInfo() has two different behaviors, which is polymorphic behavior.
Your example is very similar to one mentioned in the tutorial here: Java Tutorial : Polymorphism. So don't get confused.
The example does not demonstrate polymorphism,rather i can just see simple object oriented inheritance.In order that the concept of polymorphism be used the code should be the following.
public class FamilyDemo
{
public static void main(String ary[])
{
Family Gp = new Grandparents();
Family P1 = new Parents();
Gp.FamilyInfo();
P1.FamilyInfo();
}
}
Even though Gp is of type Family, it behaves like type Grandparents because it is initialized with an object of that type.
Then,the following may be expected:
Graparents are the elders in the family and they are the sub class of family.
The parents are the children of the grandparents and they are the sub sub class for family.
Our trainer said that using extends is more of an example of inheritance. But if we use implements(interface), we can say that it is polymorphic because we can implement many interfaces.
e.g.
interface Horse {
void run();
}
interface Eagle {
void fly();
}
public class Pegasus implements Horse, Eagle {
// Implement methods
public void run() {
// do run
}
public void fly() {
// do fly
}
}
The dictionary definition of polymorphism refers to a principle in
biology in which an organism or species can have many different forms
or stages
The basic concept is for a given object to act like another. This is achieved through the use of interfaces and inheritance in Java.
A better example of this would be (with you code as a base)
public class FamilyDemo {
public static void main(String ary[]) {
Family gp = new Grandparents();
Family p1 = new Parents();
dump(gp);
dump(p1);
}
public static void dump(Family family) {
family.FamilyInfo();
}
}
This basically allows Gradparents and Parents to "act" as they are Family
1.What is polymorphism?
In object-oriented programming, polymorphism (from the Greek meaning "having multiple forms") is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
2. Two Types of polymorphism
a) Static or Compile time Polymorphism
Which method is to be called is decided at compile-time only. Method overloading is an example of this.for example
public class calculation
{
public int add(int x, int y)
{
return x + y;
}
public int add(int x, int y, int z)
{
return x + y + z;
}
}
here you can see there are two functions with the same name but different signatures
b)Dynamic or Runtime Polymorphism.
Run time polymorphism is also known as method overriding. In this mechanism by which a call to an overridden function is resolved at a Run-Time (not at Compile-time) if a base Class contains a method that is overridden.
Class BaseClass
{
Public void show ()
{
Console.WriteLine("From base class show method");
}
}
Public Class DynamicDemo : BaseClass
{
Public void show()
{
Console.WriteLine("From Derived Class show method");
}
Public static void main(String args[])
{
DynamicDemo dpd=new DynamicDemo ();
Dpd.show();
}
}
Technically speaking, this is polymorphism. However, you have chosen a poor example and it seems like you are not quite understanding the idea behind polymorphism. A better example would be something like this.
public abstract class Shape {
public abstract void drawShape();
}
public class Rectangle extends Shape {
public void drawShape() {
// code for drawing rectangle
}
}
public class Circle extends Shape {
public void drawShape() {
// code for drawing circle
}
}
public class FilledRectangle extends Rectangle {
public void drawShape() {
super.drawShape();
// code for filling rectangle
}
}
Then a class that is responsible for the drawing doesn't need to know how to draw each individual shape. Instead, it can do this
public void drawAllShapes(Shape[] myShapes) {
for (int i = 0; i < myShapes.length; ++i) {
myShapes[i].drawShape();
}
}
The goal is to abstract away the concrete implementation and all the details that go with and instead only present a common interface. This makes it a lot easier to work with different classes, as you can see in the last method above.
A good example for polymorphism would be:
public static void print(Family[] family){
for(int i=0; i< family.length; i++){
family[i].FamilyInfo();
}
}
public static void main(String args[])
{
Family[] family = new Family[2];
Grandparents Gp = new Grandparents();
Parents P1 = new Parents();
family[0] = Gp;
family[1] = P1;
//and then send the array to another method which
//doesn't "know" which entry in the array is a parent and which is grandparent
//and there you can loop the array calling family[i].FamilyInfo();
//THIS is the whole idea of polymorphism in a nutshell
print(family);
}
Yes, in your example program you are using inherit and polimorphism, infact both are closed related.
You are using inherit because you extend once Family from Grandparents class, and once Parents class extending Grandparents and you are also using polimorphism because you are writing in your subclasses a method void FamilyInfo which is written in the super class.
You should use #Override in this way:
public class Parents extends Grandparents {
#Override
void FamilyInfo() {
System.out.println("The parents are the children of the grandparents and they are the sub sub class for family");
}
}