overloaded constructor InnerClass inside a method - java

I'm reading the book "Thinking in Java" by Bruce Eckel. I came across this assertion in the inner class chapter, which says: "the only justification for using a local inner class instead of an anonymous inner class is if you need a named constructor and/or an overloaded constructor"
I don't now if i understood well but:
Is this the way of overloading constructors of Inner(local classes) inside method?
abstract class ForInner {
abstract String getName();
abstract void setName(String newName);
abstract int getNumber();
abstract void setNumber(int newNumber);
}
class Outer{
public ForInner getSomeInner(String name) {
class LocalInner extends ForInner{
private String myName;
private int myNumber;
public LocalInner(String myName) {
this.myName = myName;
}
public String getName() {
return myName;
}
public void setName(String newName) {
myName = newName;
}
public int getNumber() {
return myNumber;
}
public void setNumber(int newNumber) {
myNumber = newNumber;
}
}
return new LocalInner(name);
}
public ForInner getSomeInner(int number) {
class LocalInner extends ForInner{
private String myName;
private int myNumber;
public LocalInner(int myNumber) {
this.myNumber = myNumber;
}
public String getName() {
return myName;
}
public void setName(String newName) {
myName = newName;
}
public int getNumber() {
return myNumber;
}
public void setNumber(int newNumber) {
myNumber = newNumber;
}
}
return new LocalInner(number);
}
}
I'm not sure if the assertion referring to this. But might have a guess that is not the case because How different it would be of using in this way
abstract class ForInner {
abstract String getName();
abstract void setName(String newName);
abstract int getNumber();
abstract void setNumber(int newNumber);
}
lass Outer{
public ForInner inner (String name) {
return new ForInner() {
private String myName;
private int myNumber;
{
myName = name;
}
public String getName() {
return myName;
}
public void setName(String newName) {
myName = newName;
}
public int getNumber() {
return myNumber;
}
public void setNumber(int newNumber) {
myNumber = newNumber;
}
};
}
public ForInner inner (int number) {
return new ForInner() {
private String myName;
private int myNumber;
{
myNumber = number;
}
public String getName() {
return myName;
}
public void setName(String newName) {
myName = newName;
}
public int getNumber() {
return myNumber;
}
public void setNumber(int newNumber) {
myNumber = newNumber;
}
};
}
}
thank in advance?

public class OuterClass {
Runnable printA = new Runnable() {
#Override
public void run() {
System.out.println("Print A");
}
};
Runnable printB = new Runnable() {
#Override
public void run() {
System.out.println("MESSAGE:" + " " + "Print B");
}
};
class PrintMessage implements Runnable {
private String msg;
public PrintMessage(String msg) {
this.msg = msg;
}
// overloaded constructor
public PrintMessage(String prefix, String msg) {
this.msg = prefix + " " + msg;
}
#Override
public void run() {
System.out.println(msg);
}
}
Runnable printC = new PrintMessage("Print C");
Runnable printD = new PrintMessage("Print D");
Runnable printE = new PrintMessage("MESSAGE:", "Print E");
public static void main(String[] args) {
OuterClass sample = new OuterClass();
sample.printA.run();
sample.printB.run();
sample.printC.run();
sample.printD.run();
sample.printE.run();
}
}
There are two instances of Runnable implemented as anonymous classes. While printA is created you cannot use it to create printB. You should create anonymous class from the beginning (i.e. override all abstract methods).
If an inner class created based on Runnable, you can use it in form new PrintMessage() to create new instances. Besides that it's possible to use non-default constructors.

Ah ok so when have this code
class OuterClass {
public Runnable printA() {
return new Runnable() {
#Override
public void run() {
System.out.println("Print A");
}
};
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
Runnable printA = outer.printA();
Runnable printB = outer.printA();
}
}
In this case I'm not creating multiply instances of a single anonymous inner class. Instead I'm creating multiple anonymous classes that use the same source code. Is that Rigth?!
Thanks

Related

Compilation error..Class cannot be resolved to a type

I have created abstract class Employee and I define a method called calculateSalary() as an abstract method. Employee abstract class is inherited by Contractor & FullTimeEmployee classes. When I try implementation of Abstract in main class I got a compiler error that shows class cannot be resolved to a type.
Employee.Class:
package Abstract;
public abstract class Employee
{
String name;
int salaryPerHour;
public Employee(String name, int salaryPerHour) {
this.name = name;
this.salaryPerHour = salaryPerHour;
}
public abstract int calculateSalary();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalaryPerHour() {
return salaryPerHour;
}
public void setSalaryPerHour(int salaryPerHour) {
this.salaryPerHour = salaryPerHour;
}
public class Contractor extends Employee
{
int workingHours;
public Contractor(String name, int salaryPerHour, int workingHours) {
super(name, salaryPerHour);
this.workingHours = workingHours;
}
#Override
public int calculateSalary()
{
return getSalaryPerHour() * workingHours;
}
}
public class FullTimeEmployee extends Employee
{
public FullTimeEmployee(String name, int salaryPerHour) {
super(name, salaryPerHour);
}
#Override
public int calculateSalary()
{
return getSalaryPerHour() * 8;
}
}
}
In Main class:
package Abstract;
public class AbstractClassExample {
public static void main(String[] args) {
Employee contractor = new Contractor("contractor", 10, 10);
Employee fullTimeEmployee = new FullTimeEmployee("full time employee", 8);
System.out.println(contractor.calculateSalary());
System.out.println(fullTimeEmployee.calculateSalary());
}
}

how to new an unknown object in abstract class

I would like to use a builder pattern to create an unknown object
how to do that?
my code like this:
public abstract class abstractA<T extends GameApplication<T>>{
public static class Builder<T> {
private JPanel panel = new JPanel();
private JFrame frame = new JFrame();
private int height = 0, width = 0;
private int x = 0,y = 0;
private Color backgroundColor = Color.BLUE;
public Builder setFrameHeightWidth(int height, int weight) {
this.height = height;
this.width = weight;
return this;
}
public Builder setLocation(int x, int y) {
this.x = x;
this.y = y;
return this;
}
public Builder setbackground(Color color) {
this.backgroundColor = color;
return this;
}
public T Build(){
//error here
return new T ;
}
}
I want to use it like this:
class RealA extends abstractA{
public static void main(String[] argv){
RealA a = abstractA.builder
.setLocation(100,200)
.setFrameHeightWidth(500,600)
.build();
}
}
and I can't create a generics object, but I need this. How to do that?
You can sort of do (something like) this if you let the builder know the kind of thing it is building (by passing it a class) and then get it to create the instance using reflection (e.g. the classes newInstance method).
This assumes all sub classes have a zero-argument constructor. (It can be modified to use a constructor with arguments, but each sub-class would need a constructor with the same signature)
For example...
public class Stack {
static abstract class Common {
protected String name;
public void setName(String name) {
this.name = name;
}
public abstract void doSomething();
}
static class Solid1 extends Common {
#Override
public void doSomething() {
System.out.println("Solid1's implementation: name=" + name);
}
}
static class Solid2 extends Common {
#Override
public void doSomething() {
System.out.println("Solid2's implementation: name=" + name);
}
}
static class Builder<T extends Common> {
private final Class<T> clazz;
private String name;
public Builder(Class<T> clazz) {
this.clazz = clazz;
}
public Builder<T> setName(String name) {
this.name = name;
return this;
}
public T build() {
T t;
try {
t = clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException("Bad things have happened!");
}
t.setName(name);
return t;
}
}
public static void main(String[] args) {
Solid1 solid1 = new Builder<>(Solid1.class).setName("[NAME]").build();
Solid2 solid2 = new Builder<>(Solid2.class).setName("[NAME]").build();
solid1.doSomething();
solid2.doSomething();
}
}
Output...
Solid1's implementation: name=[NAME]
Solid2's implementation: name=[NAME]
Not sure how useful this is...

How to acces a void method from another class?

how do I call a void method from another class to a new class with main?
I have two classes, but I don't see the error I am making.
public class Person {
private int age;
private String name;
public Person(int a, String n) {
a = age;
n = name;
}
public void printInfo() {
System.out.println(age + name);
}
//
public class Main {
public static void main(String[] args) {
Person obj1 = new Person(22, "Dan");
obj1.printInfo();
}
}
EDIT: Move the main method to a different class and done.
TestPerson.java
public class TestPerson {
public static void main(String[] args) {
Person obj1 = new Person(22, "Dan");
obj1.printInfo();
}
}
You have few mistakes in your code. It should be like as follows :
public class Person {
private int age;
private String name;
//Your constructor was wrong
public Person(int a, String n) {
age = a;
name = n;
}
public void printInfo() {
System.out.println(age + name);
}
}

can i print a setter value (sysout) or do i have to use only getters in order to get an output ? (java)

I have just recently learned about setter , getters and this.(somthing).
I having quite a hard time undersatnding when to use getters and when to use setters .
Another thing , can i use setter method to print out ?
For Example :
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
newAge = workerAge;
}
public void setWorkerName(String newName) {
newName = workerName;
}
public int setIde(int ide) {
ide = workerIde;
return ide;
}
}
public class App {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.setIde());
}
}
the system out print shows an error and i didnt understand why , is it because only getters can be used in the sysout command ?
No offense intended, but your setters are all wrong. You should assign your properties to the values passed in the setter, not setting the value again. So your code should look like this:
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName = newName;
}
public int setIde(int ide) {
workerIde = ide;
}
}
If you need getters, it should look like this:
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName = newName;
}
public int setIde(int ide) {
workerIde = ide;
}
public int getIde() {
return workerIde;
}
}
Then you can print, e.g. System.out.println(worker1.getIde());
You should be using a getter method to get the values.
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName=newName;
}
public int getIde() {
return workerIde;
}
public void setIde(int ide) {
workerIde = ide;
}
}
public class App {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.getIde());
}
}
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
this.workerAge = newAge;
}
public void setWorkerName(String newName) {
this.workerName = newName;
}
public int setIde(int ide) {
this.workerIde = ide;
return this.workerIde;
}
}
public class Car {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.setIde(56));
}
}

How to add value from another class (java)

I have two classes: profesor and subject
public class Profesor {
private int numbClassroom;
public Profesor(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String ToString(){
return "Number of classroom: "+numbClassroom;
} }
The second class is:
public class Subject{
String name;
Profesor lecturer = new Profesor();
Date yearOfStudy;
public void Dodeli(Profesor p){
??????
}}
I do not know how to add professor like a lecturer to a current subject
Like this? I don't see any problem.
public void Dodeli(Profesor p){
lecturer = p;
}
Profesor lecturer = new Profesor();
No need to instantiate lecturer. Just declare it. Then have getter/setter methods for it
Then you can assign Professor to Subject
Subject subj = new Subject("OOP"); //assuming you have corresponding constructor
subj.setLecturer(new Professor()); //or if you have existing prof object
Maybe require something like this : try to encapsulate your code
public class Professor {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Subject{
private String name;
private Professor professor;
private int numbClassroom;
private Date yearOfStudy;
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Professor getProfesor() {
return professor;
}
public void setProfesor(Professor profesor) {
this.professor = profesor;
}
public void Dodeli(){
System.out.println("Pofessor "+getProfesor().getName()+" is teaching "+getName()+" in Room NO :"+getNumbClassroom());
}
}
public class TestImpl {
public static void main(String arr[])
{
Subject subject = new Subject();
Professor professor = new Professor();
subject.setName("Biology");
professor.setName("MR.X");
subject.setNumbClassroom(1111);
subject.setProfesor(professor);
subject.Dodeli();
}
}

Categories