1.继承:
父类:
public class Person
{
int age;
String name;
int sex;
public void showInfo()
{
System.out.println(this.age);
System.out.println(this.name);
System.out.println(this.sex);
}
}
子类:
/**
* 子类
* @author Daniel
*
*/
public class Student extends Person
{
String school;
public void showInfo()
{
System.out.println(this.age);
System.out.println(this.name);
System.out.println(this.sex);
System.out.println(this.school);
}
}
语法:class Subclass extends Superclass{}
1.提高了代码的复用性;
2.实现多态;
3.不要仅为了某个类中的功能去继承。
子类不是父类的子集,而是拓展。
2.单继承:
public class ManKind
{
int sex;
int salary;
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public void manOrwomen()
{
if (this.sex == 1)
{
System.out.println("man");
}
else if(this.sex == 0)
{
System.out.println("women");
}
}
public void employeed()
{
if (this.salary == 0)
{
System.out.println("no job");
}
else
{
System.out.println("job");
}
}
}
public class Kids extends ManKind
{
int yearsOld;
public int getYearsOld() {
return yearsOld;
}
public void setYearsOld(int yearsOld) {
this.yearsOld = yearsOld;
}
public void printAge()
{
System.out.println(this.yearsOld);
}
public static void main(String[] args)
{
Kids someKid = new Kids();
someKid.setSex(0);
someKid.setSalary(100);
someKid.manOrwomen();
someKid.employeed();
}
}
3. this\super:
4.多态:
表现:
1.方法的重载(overload)和重写(overwrite);
2.对象的多态–>可以直接应用在抽象类和接口。
public static void main(String[] args)
{
Person p = new Person();
Student e = new Student();
p = new Student();
//当前p引用了student的实例对象
//向上转型,把子类的对象给父类类型对象引用
}
5.instanceof 操作符:
x instanceof A: 检验x是否为类A的对象,返回值为boolean型
Student s = new Student();
Person p = new Person();
System.out.println(s instanceof Person);
System.out.println(p instanceof Person);
System.out.println(p instanceof Student);
6.Object类:
根父类,基类。
主要方法:
public class Test
{
/**
* 问题,想给test方法设置一个形参,这个参数不确定会传进来什么,可以传递的实参一定会是一个类
*/
public void test(object obj)
{
public static void main(String[] args)
{
Test t = new Test();
Person p = new Person();
Student s = new Student();
t.test(p);
t.test(s);
t.test(new Kk());
}
}
}