java基础篇(四)——C中struct和java中class

一、C语言中的struct

#include <stdio.h>

struct person {
	char *name;
	/*面向对象思想,为实现分层*/
	void (*printName)(struct person *per);
};

void printName(struct person *per)
{
	printf("guangdong %s\n", per->name);
}

int main(void)
{
	struct person p1 = {"zhangsan", printName};
	struct person p2 = {"lisi", printName};

	//printf("%s\n", p1.name);
	//printf("%s\n", p2.name);
	p1.printName(&p1);
	p2.printName(&p2);

	return 0;
}

二、java中的class

class Person {

	static int count;
	
	String name;
	int age;
	String getName() {
		return "guangdong "+name;
	}
	/*静态代码块*/
	static {
		System.out.println("static block");		
	}
	/*构造代码块*/
	{
		System.out.println("construct block");
		count ++;
	}

	/* construct method */	
	/*无参数构造方法*/
	public Person () {
		System.out.println("construct method: Person 1");
		name = "null";
		age  = 0;
	}
	/*有参数构造方法*/
	public Person (String name) {
		System.out.println("construct method: Person 2");
		this.name = name;
	}

	public Person (String name, int age) {
		System.out.println("construct method: Person 3");
		this.name = name;
		this.age  = age; 
	}

	static void printPerson () {
		System.out.println("This is a class of Person");
	}
	
};


public class Oop5 {
	public static void main(String args[]) {
		Person p1 = new Person("zhangsan");
		Person p2 = new Person("lisi");
		Person p3 = new Person();
		Person p4 = new Person("wangwu", 6);

		System.out.println(p1.getName());
		System.out.println(p2.getName());
		System.out.println(p3.getName());
		System.out.println(p4.getName());

		Person.printPerson();
		System.out.println(Person.count);
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值