BAEL-3966: find object's class in Java (#9118)

This commit is contained in:
Aaron Juarez 2020-04-25 16:23:13 -04:00 committed by GitHub
parent b7588a7a33
commit ee898632d3
4 changed files with 129 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package com.baeldung.objectclass;
import lombok.Data;
@Data
public class Borrower extends User {
private double totalLoanAmount;
public double requestLoan(double amount) {
totalLoanAmount = amount;
return totalLoanAmount;
}
public double increaseLoan(double increaseBy) {
return totalLoanAmount + increaseBy;
}
public double payLoan(double amount) {
return totalLoanAmount - amount;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.objectclass;
public class Lender extends User {
private double totalInvestmentAmount;
public double invest(double amount) {
totalInvestmentAmount = amount;
return totalInvestmentAmount;
}
public double increaseInvestment(double increaseBy) {
return totalInvestmentAmount + increaseBy;
}
public double collectDividends() {
return totalInvestmentAmount * 0.07;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.objectclass;
import lombok.Data;
@Data
public class User {
private String firstName;
private String lastName;
}

View File

@ -0,0 +1,74 @@
package com.baeldung.objectclass;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class CreditAppUnitTest {
@Test
public void givenLender_whenInstanceOf_thenReturnTrue() {
User lender = new Lender();
assertTrue(lender instanceof Lender);
assertTrue(lender instanceof User);
}
@Test
public void givenUser_whenInstanceOfLender_thenDowncast() {
User user = new Lender();
Lender lender = null;
if(user instanceof Lender) {
lender = (Lender) user;
}
assertNotNull(lender);
}
@Test
public void givenUser_whenIsInstanceOfLender_thenDowncast() {
User user = new Lender();
Lender lender = null;
if(Lender.class.isInstance(user)) {
lender = (Lender) user;
}
assertNotNull(lender);
}
@Test
public void givenBorrower_whenLoanAmountIsDouble_thenRequestLoan() {
Borrower borrower = new Borrower();
double amount = 100.0;
//if(amount instanceof Double) // Compilation error, no autoboxing
if(Double.class.isInstance(amount)) {
borrower.requestLoan(amount);
}
assertEquals(100, borrower.getTotalLoanAmount());
}
@Test
public void givenBorrower_whenLoanAmountIsNotString_thenRequestLoan() {
Borrower borrower = new Borrower();
Double amount = 100.0;
//if(amount instanceof String) // Compilation error, incompatible operands
if(!String.class.isInstance(amount)) {
borrower.requestLoan(amount);
}
assertEquals(100, borrower.getTotalLoanAmount());
}
@Test
public void givenLender_whenGetClass_thenEqualsLenderType() {
User lender = new Lender();
assertEquals(Lender.class, lender.getClass());
assertNotEquals(User.class, lender.getClass());
}
}